﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using IntfClass;
using IntfSetting;
using IntfSetting.FrmIntf;

using SunLightIntfService;
using Application = System.Windows.Forms.Application;
using DataTable = System.Data.DataTable;
using System.Data.OleDb;
using System.Text.RegularExpressions;
using _Excel = Microsoft.Office.Interop.Excel;    
using Microsoft.Office.Interop.Excel;  



namespace 配置工具界面美化 {
    public partial class Form1 : Form {
        private string FilePath = null;
        private Boolean blnNew = false;
        private Boolean blnNewForDMS = true;
        private DataTable dtData = new DataTable();
        private string url = Application.StartupPath + @"\Skins";//皮肤文件夹地址
        private int count = 0;
        private string StyleUrl = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Config\\CfgXML.xml";  //皮肤信息存储XML位置
        private string StatueUrl = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "ComboboxData\\Statue.xml";  //上传状态存储XML位置
        private string dmsCode = "";
        private DataTable StatueTable;
        private DataTable datGridView = new DataTable();
        private string strID = string.Empty;
        public DataTable datWebService = new DataTable();
        private DataRow[] dataRows = new DataRow[1];
        private DataTable dtDir = new DataTable();
        private DataTable dtGridView = new DataTable();
        public static DataTable datGridViewFroDMS = new DataTable();
        DataTable dtForInterfaceInport;
        DataSet dsForDataInport;
        private string urlForDataInport;
        private DataTable dtDataForFilePath = new DataTable();

        private int searchCount = 0;
        private int searchIntfNameCount = 0;

        public int blNameCode = 0;

        public int iRowCount = 0;

        public Form1() {
            InitializeComponent();
            
            Cmb_Statue.SelectedText = "不限";
            
            //初始化
            try {
                SetFormTitle();
                FrmWebServiceNew_Load();
                FrmWebServiceMain_Load();
                FrmClassMain_Load(); //
                FrmBuinessNew_Load(); //初始化磁盘文件系统存储路径
                FrmDCSUrl_Load();
                FrmCfgFre_Load(); //初始化下发时间  感觉这个字段好奇怪
                FrmIntfMain_Load(); //初始化接口信息页面
                FrmLog_Load(); //初始化文件查询日志界面
                // skinEngine1.SkinFile = Application.StartupPath + @"\Skins\Wave.ssk";//Wave蓝色风格，默认值
                //throw new Exception();
            } catch(Exception ex) {
                MessageBox.Show("初始化失败,请查看配置文件是否存在，或者正确配置" + AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "DataBase.txt" + ex);
            }
            try {
                //取得皮肤配置信息
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(StyleUrl);
                //xmlDocument.Load(System.Environment.CurrentDirectory + "\\" + "Config\\CfgXML.xml");
                XmlNode xmlNode = xmlDocument.SelectSingleNode("CFG/DMS");
                dmsCode = xmlNode.FirstChild.Value;
                //skinEngine1.SkinFile = Application.StartupPath + @"\Skins\" + dmsCode;//根据之前保存的信息进行皮肤设置
            } catch(Exception) {
            }
            SetList(url); //获取现有皮肤列表
            DataSet ds = new DataSet();
            ds.ReadXml(StatueUrl); //路径需要改DataTable dt = ds.Tables[0];
            StatueTable = ds.Tables["content"];
            Cmb_Statue.DataSource = StatueTable;
            Cmb_Statue.DisplayMember = "statue";//绑定泛型中类的属性
            Cmb_Statue.ValueMember = "code";
            //serachDMSCode
            //获取所有接口信息，并添加到List Record By ZFX 2014-09-22
            RefleshchkListFun();
            //获取所有接口信息，并添加到List Record By ZFX 2014-09-22
            RefleshChkList();
        }

        private void RefleshchkListFun() {
            DataTable dtChkList = this.serachIntfCode();
            foreach(DataRow item in dtChkList.Rows) {
                //this.chkListFun.Items.Add(item["Code"].ToString());
                this.chkListFun.Items.Add(item["Name"].ToString());
            }
        }

        private void RefleshChkList() {
            DataTable dtchkListDMS = this.serachDMSCode(0);
            chkListDMS.Items.Clear();
            foreach(DataRow item in dtchkListDMS.Rows) {
                this.chkListDMS.Items.Add(item["SysCode"].ToString());
            }
        }

        #region 获取接口信息
        private DataTable serachIntfCode() {
            StringBuilder strSql = new StringBuilder();
            //改为显示中文名
            //strSql.AppendLine("Select t.code from TIntf t");
            //strSql.AppendLine("Select t.name from TIntf t order by t.code");
            strSql.AppendLine("Select t.name from TIntf t");
            DataTable dtData = new DataTable();
            ClassDB classDB = new ClassDB();
            dtData = classDB.ExecuteDataTable(strSql.ToString());
            return dtData;
        }
        #endregion


        #region 获取接口信息
        private DataTable serachDMSCode(int DMSorAllList) {
            StringBuilder strSql = new StringBuilder();
            //这种是获取多有出现在日志的Tlog的系统
            if(DMSorAllList == 1) {

                //strSql.AppendLine("select distinct(SysCode) from TLog  order by SysCode ");
                strSql.AppendLine("select distinct(SysCode) from TSideList  order by SysCode ");
            } else {

                strSql.AppendLine(@"select o.SysCode
                              from Tside t,TSideList o
                              where t.ID = o.ParentID
                              and t.Code = 'DMS'
                              union all
                              select 'DCS'");
            }
            DataTable dtData = new DataTable();
            ClassDB classDB = new ClassDB();
            dtData = classDB.ExecuteDataTable(strSql.ToString());
            return dtData;
        }
        #endregion
        public void SetList(string url) {
            DataTable dttempStyle = GetStyle(url);
            DataRow dr = dttempStyle.NewRow();
            dr[0] = "";
            dttempStyle.Rows.InsertAt(dr, 0);
            Cmb_Style.DataSource = dttempStyle;
            Cmb_Style.DisplayMember = "Style";//绑定泛型中类的属性
            Cmb_Style.ValueMember = "Style";
            Cmb_Style.SelectedValue = dmsCode;
        }
        private DataTable searchData2(string sql) {
            ClassDB classDB = new ClassDB();
            DataTable dataTable = classDB.ExecuteDataTable(sql);
            return dataTable;
        }
        private void FrmCfgFre_Load() {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("select * from TSave t");
            dtDir = searchData2(strSql.ToString());
            if(dtDir.Rows.Count == 0) {
                MessageBox.Show("请先设置存储路径！");
                return;
            }
            double dblMM = 0;
            if(!string.IsNullOrEmpty(dtDir.Rows[0]["cfgFre"].ToString())) {
                dblMM = double.Parse(dtDir.Rows[0]["cfgFre"].ToString());
            }
            int hour = Convert.ToInt16(Math.Floor(dblMM / (1000 * 60 * 24)));
            int min = Convert.ToInt16(Math.Floor((dblMM - hour * (1000 * 60 * 24)) / (1000 * 60)));
            this.txt_down_Hour.Text = hour.ToString();
            this.txt_down_Minunter.Text = min.ToString();
        }

        public DataTable GetStyle(string url) {
            string filepath = url;
            string[] filenames = Directory.GetFiles(filepath);  //获取该文件夹下面的所有文件名
            var files = Directory.GetFiles(url, "*ssk");
            DataTable dt = CreateStyleTable();
            foreach(var file in files)  //循环判断每一个文件是否是目录（即文件夹）
                {
                DataRow dataRow = dt.NewRow();
                dataRow["Style"] = Path.GetFileName(file);
                dt.Rows.Add(dataRow);
            }
            //Console.WriteLine("文件夹名为"+fname);
            return dt;
        }
        #region 创建一个数据返回表结构
        public DataTable CreateStyleTable() {
            DataTable datatable = new DataTable();
            DataColumn Style = new DataColumn("Style", Type.GetType("System.String"));
            datatable.Columns.AddRange(new DataColumn[] { Style });
            return datatable;
        }
        #endregion

        private void Cmb_Style_SelectedValueChanged(object sender, EventArgs e) {
            if(count > 0) {

                try {
                    if(Cmb_Style.Text == "") {
                        //skinEngine1.Active = false;
                    } else {
                        //skinEngine1.Active = true;
                        //skinEngine1.SkinFile = Application.StartupPath + @"\Skins\" + Cmb_Style.Text;
                        //office2007风格，感觉不错 5
                    }
                } catch(Exception) {
                }
            }
            count++;
        }

        private void BtnChangeStyle_Click(object sender, EventArgs e) {
            XmlDocument doc = new XmlDocument();
            doc.Load(StyleUrl);
            XmlNode root = doc.DocumentElement;
            XmlNode DMS = root.SelectSingleNode("DMS");
            DMS.InnerText = Cmb_Style.Text;
            doc.Save(StyleUrl);
        }

        private void btnReturn_Click(object sender, EventArgs e) {
            //skinEngine1.SkinFile = Application.StartupPath + @"\Skins\" + dmsCode;//根据之前保存的信息进行皮肤设置
            Cmb_Style.SelectedValue = dmsCode;
            XmlDocument doc = new XmlDocument();
            doc.Load(StyleUrl);
            XmlNode root = doc.DocumentElement;
            XmlNode DMS = root.SelectSingleNode("DMS");
            DMS.InnerText = Cmb_Style.Text;
            doc.Save(StyleUrl);
        }

        private void button1_Click(object sender, EventArgs e) {
            string strIN = string.Empty;
            string strDMS = string.Empty;

            string strIN1 = string.Empty;

            //for(int i = 0; i < chkListFun.Items.Count; i++) {
            //    if(chkListFun.GetItemChecked(i)) {
            //        strIN = strIN + "'" + chkListFun.GetItemText(chkListFun.Items[i]) + "',";
            //    }
            //}
            int j = 0;
            for(int i = 0; i < chkListFun.Items.Count; i++) {
                if(chkListFun.GetItemChecked(i)) {
                    if(j > 0) {
                        strIN1 = strIN1 + ",'" + chkListFun.GetItemText(chkListFun.Items[i]) + "'";
                    } else
                        strIN1 = strIN1 + "'" + chkListFun.GetItemText(chkListFun.Items[i]) + "'";
                    j = j + 1;
                }
            }

            for(int i = 0; i < chkListDMS.Items.Count; i++) {
                if(chkListDMS.GetItemChecked(i)) {
                    strDMS = strDMS + "'" + chkListDMS.GetItemText(chkListDMS.Items[i]) + "',";
                }
            }

            //修改成取Name
            StringBuilder strSqlName = new StringBuilder();
            strSqlName.AppendLine("Select t.Code from TIntf t");
            if(!(strIN1 == "")) {
                if(blNameCode == 1) {
                    strSqlName.AppendLine("Where t.code in (" + strIN1 + ")");
                } else {
                    strSqlName.AppendLine("Where t.Name in (" + strIN1 + ")");
                }

            }

            ClassDB classDB1 = new ClassDB();

            int k = 0;
            DataTable dt1 = classDB1.ExecuteDataTable(strSqlName.ToString());
            for(int i = 0; i < dt1.Rows.Count; i++) {

                //if (k>0) {
                //strIN = strIN + ",'" + dt1.Rows[i][0].ToString() + "'";
                //}
                //else
                //strIN = strIN + "'" + dt1.Rows[i][0].ToString() + "'";

                //k = k + 1;
                strIN = strIN + "'" + dt1.Rows[i][0] + "',";

            }



            StringBuilder strSql = new StringBuilder();
            //strSql.AppendLine("Select t.ID,t.IntfCode,t.SysCode,t.SyncNo");
            //strSql.AppendLine(",case t.Status when 0 then '失败'");
            //strSql.AppendLine("			      when 1 then '成功' end as Status");
            //strSql.AppendLine(",t.ErrMsg,t.URL,t.SendTime,t.LogDir from TLog t");

            strSql.AppendLine("Select t.ID,f.Name,t.SysCode,t.SyncNo");
            strSql.AppendLine(",case t.Status when 0 then '失败'");
            strSql.AppendLine("			      when 1 then '成功' end as Status");
            strSql.AppendLine(",t.ErrMsg,t.URL,t.SendTime,t.LogDir,t.IntfCode from TLog t,TIntf f");

            strSql.AppendLine("Where 1 = 1 and t.IntfCode=f.Code");
            //取掉多余的‘，’
            if(!strIN.Equals(string.Empty)) {
                strIN = strIN.Remove(strIN.Length - 1, 1);
                strSql.AppendLine("and t.IntfCode in (" + strIN + ")");
            }
            if(!strDMS.Equals(string.Empty)) {
                strDMS = strDMS.Remove(strDMS.Length - 1, 1);
                strSql.AppendLine("and t.SysCode in (" + strDMS + ")");
            }
            if(this.Cmb_Statue.Text == "不限") {
            } else if(this.Cmb_Statue.Text == "成功") {
                strSql.AppendLine("and t.Status = 1");
            } else if(this.Cmb_Statue.Text == "失败") {
                strSql.AppendLine("and t.Status = 0");
            }
            strSql.AppendLine("and t.SendTime > @startTime");
            strSql.AppendLine("and t.SendTime <= @endTime");
            SqlParameter sqlParameter1 = new SqlParameter("startTime", SqlDbType.DateTime);
            sqlParameter1.Value = new DateTime(dateTimePicker1.Value.Year, dateTimePicker1.Value.Month, dateTimePicker1.Value.Day, dateTimePicker3.Value.Hour, dateTimePicker3.Value.Minute, 0);
            SqlParameter sqlParameter2 = new SqlParameter("endTime", SqlDbType.DateTime);
            sqlParameter2.Value = new DateTime(dateTimePicker2.Value.Year, dateTimePicker2.Value.Month, dateTimePicker2.Value.Day, dateTimePicker4.Value.Hour, dateTimePicker4.Value.Minute, 0); ;
            ClassDB classDB = new ClassDB();
            DataTable dt = classDB.ExecuteDataTable(strSql.ToString(), new SqlParameter[] { sqlParameter1, sqlParameter2 });
            this.dataGridView1.DataSource = dt;
            TbCountRows.Text = dt.Rows.Count.ToString();
            dataGridView1.Columns[0].Visible = false;
            dataGridView1.Columns[1].Visible = true;
            dataGridView1.Columns[2].Visible = true;
            dataGridView1.Columns[3].Visible = true;
            dataGridView1.Columns[4].Visible = true;
            dataGridView1.Columns[5].Visible = true;
            dataGridView1.Columns[6].Visible = true;
            dataGridView1.Columns[7].Visible = true;
            dataGridView1.Columns[8].Visible = true;
            dataGridView1.Columns[9].Visible = false;
            dataGridView1.Columns[1].ReadOnly = true;
            dataGridView1.Columns[2].ReadOnly = true;
            dataGridView1.Columns[3].ReadOnly = true;
            dataGridView1.Columns[4].ReadOnly = true;
            dataGridView1.Columns[5].ReadOnly = true;
            dataGridView1.Columns[6].ReadOnly = true;
            dataGridView1.Columns[7].ReadOnly = true;
            dataGridView1.Columns[8].ReadOnly = true;

            dataGridView1.Columns[8].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView1.Columns[1].HeaderText = "接口方法";
            dataGridView1.Columns[2].HeaderText = "系统编号";
            dataGridView1.Columns[3].HeaderText = "数据行号";
            dataGridView1.Columns[4].HeaderText = "状态";
            dataGridView1.Columns[5].HeaderText = "信息";
            dataGridView1.Columns[6].HeaderText = "URL";
            dataGridView1.Columns[7].HeaderText = "执行时间";
            dataGridView1.Columns[8].HeaderText = "源文件";
        }

        private void SetFormTitle() {
            //取得数据库连接信息
            String strFilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Title.txt";

            if(File.Exists(strFilePath)) {


                StreamReader reader = new StreamReader(strFilePath, Encoding.Default);
                String strTitle = reader.ReadLine().Trim();
                //int LineNo = 0;
                //String strTile = "";
                //String strDataBase = "";
                //while(!reader.EndOfStream) {
                //    if(LineNo == 2) {
                //        strTile = reader.ReadLine().Trim();
                //    }
                //    if(LineNo == 1) {
                //        strDataBase = reader.ReadLine().Trim();
                //    }

                //    LineNo = LineNo + 1;
                //}
                if(!string.IsNullOrEmpty(strTitle)) {
                    this.Text = strTitle;
                    //this.BackColor=Color.Blue;
                }
                

                reader.Close();
            }
        }

        private void FrmWebServiceNew_Load() {
            string strSql = "select t.ID,t.ParentID,t.SysCode,t.Address from TSideList t , TSide o where o.Code = 'DMS' and t.ParentID = o.ID ";
            ClassDB classDB = new ClassDB();
            datGridViewFroDMS = classDB.ExecuteDataTable(strSql);
            if(datGridViewFroDMS.Rows.Count > 0) {
                blnNewForDMS = false;
                strID = datGridViewFroDMS.Rows[0]["ParentID"].ToString();
            } else {
                blnNewForDMS = true;
            }
            //dgv_MS.DataSource = datGridViewFroDMS;
            //dgv_MS.Columns[0].Visible = false;
            //dgv_MS.Columns[1].Visible = false;
            //dgv_MS.Columns[2].Visible = true;
            //dgv_MS.Columns[3].Visible = false;
            //dgv_MS.Columns[2].ReadOnly = true;
            //dgv_MS.Columns[3].ReadOnly = true;
            //dgv_MS.Columns[2].HeaderText = "系统编号";
            //dgv_MS.Columns[3].HeaderText = "URL";
            //dgv_MS.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
        }

        private DataTable searchData() {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("select o.* from TSide t,TSideList o");
            strSql.AppendLine("where t.Code = 'DCS'");
            strSql.AppendLine("and t.ID = o.ParentID");
            ClassDB classDB = new ClassDB();
            DataTable dataTable = classDB.ExecuteDataTable(strSql.ToString());
            return dataTable;
        }

        private void FrmDCSUrl_Load() {
            dtData = searchData();
            if(dtData.Rows.Count > 0) {
                txtURL.Text = dtData.Rows[0]["Address"].ToString();
            } else {
                blnNew = true;
            }
        }

        #region 保存DCS信息
        private void btnSave_Click(object sender, EventArgs e) {
            ClassDB ClassDB = new ClassDB();
            StringBuilder strSql = new StringBuilder();
            SqlConnection conn = ClassDB.CreateConnection();
            conn.Open();
            SqlTransaction sqlTransaction = conn.BeginTransaction();
            try {
                if(blnNew) {
                    strSql.AppendLine("Insert into Tside( Code, Name) values ('DCS','DCS')");
                    ClassDB classDB = new ClassDB();
                    long longID = classDB.ExecuteID(strSql.ToString(), conn, sqlTransaction, null);
                    DataRow dataRow = dtData.NewRow();
                    dataRow["ParentID"] = longID;
                    dataRow["SysCode"] = "DCS";
                    dataRow["Address"] = this.txtURL.Text.Trim();
                    dtData.Rows.Add(dataRow);
                    classDB.ExecuteBulkInsert("TSideList", dtData, conn, sqlTransaction);
                } else {
                    strSql.AppendLine("Update Tsidelist set Address = '" + this.txtURL.Text.Trim() + "'");
                    strSql.AppendLine("Where parentid =" + dtData.Rows[0]["ParentID"]);
                    ClassDB classDB = new ClassDB();
                    classDB.ExecuteNone(strSql.ToString(), conn, sqlTransaction, null);
                }
                sqlTransaction.Commit();
                MessageBox.Show("保存成功！");
            } catch(Exception ex) {
                sqlTransaction.Rollback();
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void btnSaveDMSCode_Click(object sender, EventArgs e) {
            if(datGridViewFroDMS.Rows.Count > 0) {
                blnNew = false;
                strID = datGridViewFroDMS.Rows[0]["ParentID"].ToString();
            } else {
                blnNew = true;
            }
            FrmSetDMSCode frmSetDMSCode = new FrmSetDMSCode(string.Empty, datGridViewFroDMS);
            frmSetDMSCode.ShowDialog();
            //dgv_MS.DataSource = datGridViewFroDMS;
        }

        //DMS上的按钮
        private void button4_Click(object sender, EventArgs e) {
            {
                if(ofdCSV.ShowDialog() == DialogResult.Cancel) {
                    return;
                }
                //csv文件读取
                DataTable dt = ClassCSV.ReadCsv(ofdCSV.FileName);
                //DataSet dataSet = ClassCSV.ImportCSV(System.IO.Path.GetDirectoryName(ofdCSV.FileName), System.IO.Path.GetFileName(ofdCSV.FileName));
                DataSet dataSet = new DataSet();
                dataSet.Tables.Add(dt);
                Int64 intParentID = 0;
                if(datGridViewFroDMS.Rows.Count > 0) {
                    intParentID = Convert.ToInt64(datGridViewFroDMS.Rows[0]["ParentID"].ToString());
                }
                //datGridViewFroDMS.Rows.Clear();
                for(int i = 0; i < dt.Rows.Count; i++) {
                    DataRow dataRow = datGridViewFroDMS.NewRow();
                    dataRow["ParentID"] = intParentID;
                    dataRow["SysCode"] = dt.Rows[i][0];
                    dataRow["Address"] = "localhost";
                    datGridViewFroDMS.Rows.Add(dataRow);
                }
                //dgv_MS.DataSource = datGridViewFroDMS;
            }
        }

        private void button3_Click(object sender, EventArgs e) {
            //while(dgv_MS.SelectedRows.Count > 1) {
            //    datGridViewFroDMS.Rows.RemoveAt(dgv_MS.SelectedRows[0].Index);
            //}
            //if(dgv_MS.SelectedRows.Count > 0)
            //    datGridViewFroDMS.Rows.RemoveAt(dgv_MS.SelectedRows[0].Index);
        }

        private Boolean CheckData() {
            try {
                Boolean blnReturn = true;
                //if(dgv_MS.Rows.Count == 0) {
                //    MessageBox.Show("DMS清单不可为空");
                //    btnSaveDMSCode.Focus();
                return false;
                //}
                return blnReturn;
            } catch(Exception) {
                return false;
            }
        }


        private void FrmWebServiceMain_Load() {
            try {
                string strSql = "select t.ID,t.code,t.name from Tside t where t.code <> 'DCS' ";
                ClassDB classDB = new ClassDB();
                datGridView = classDB.ExecuteDataTable(strSql);
                Dgv_Other.DataSource = datGridView;
                Dgv_Other.Columns[0].Visible = false;
                Dgv_Other.Columns[1].Visible = true;
                Dgv_Other.Columns[2].Visible = true;
                Dgv_Other.Columns[1].ReadOnly = true;
                Dgv_Other.Columns[2].ReadOnly = true;
                Dgv_Other.Columns[1].HeaderText = "编号";
                Dgv_Other.Columns[2].HeaderText = "名称";

            } catch(Exception ex) {
                MessageBox.Show("FrmWebServiceMain_Load()加载失败");
            }
        }


        private void button5_Click(object sender, EventArgs e) {
            if(!CheckData()) {
                return;
            }
            Int64 intId = 0;
            StringBuilder strSql = new StringBuilder();
            ClassDB classDB = new ClassDB();
            SqlConnection conn = classDB.CreateConnection();
            conn.Open();
            SqlTransaction sqlTransaction = conn.BeginTransaction();
            try {
                if(blnNew) {
                    SqlParameter sqlParCode = new SqlParameter("Code", SqlDbType.NVarChar, 50);
                    sqlParCode.Value = "DMS";
                    SqlParameter sqlParName = new SqlParameter("Name", SqlDbType.NVarChar, 50);
                    sqlParName.Value = "DMS";
                    SqlParameter[] sqlParameters = { sqlParCode, sqlParName };
                    strSql.AppendLine("Insert into Tside( Code, Name) values (@Code,@Name)");
                    intId = classDB.ExecuteID(strSql.ToString(), conn, sqlTransaction, sqlParameters);
                } else {
                    SqlParameter sqlParParentID = new SqlParameter("ParentID", SqlDbType.Int);
                    sqlParParentID.Value = Convert.ToInt64(strID);
                    strSql = new StringBuilder();
                    strSql.AppendLine("Delete from TSideList where ParentID = @ParentID");
                    classDB.ExecuteNone(strSql.ToString(), conn, sqlTransaction, new SqlParameter[] { sqlParParentID });
                    intId = Convert.ToInt64(strID);
                }
                for(int i = 0; i < datGridViewFroDMS.Rows.Count; i++) {
                    datGridViewFroDMS.Rows[i]["ParentID"] = intId;
                    datGridViewFroDMS.Rows[i]["Address"] = "localhost";
                }
                classDB.ExecuteBulkInsert("TSideList", datGridViewFroDMS, conn, sqlTransaction);
                sqlTransaction.Commit();
                MessageBox.Show("保存成功！");
                RefleshchkListDMS();
            } catch(Exception ex) {
                sqlTransaction.Rollback();
                MessageBox.Show(ex.Message);
            } finally {
                conn.Close();
                conn.Dispose();
            }
        }

        private void SearchGridView() {
            string strSql = "select t.ID,t.code,t.name from Tside t where t.code <> 'DCS'";
            ClassDB classDB = new ClassDB();
            datGridView = classDB.ExecuteDataTable(strSql);
            Dgv_Other.DataSource = datGridView;
        }

        private void btnOtherDel_Click(object sender, EventArgs e) {
            if(Dgv_Other.SelectedRows[0].Cells["Code"].Value == null) {
                return;
            }

            DialogResult dialogResult = MessageBox.Show("确认删除" + Dgv_Other.SelectedRows[0].Cells["Code"].Value.ToString() + "?",
                this.Text, MessageBoxButtons.OKCancel);
            if(dialogResult == DialogResult.OK) {
                //删除
                string strID = Dgv_Other.SelectedRows[0].Cells["ID"].Value.ToString();
                string strSql = "delete from Tsidelist where parentid =" + strID + " ; ";
                strSql = strSql + "delete from Tside where id =" + strID;
                ClassDB classDB = new ClassDB();
                classDB.ExecuteTransaction(strSql);
                MessageBox.Show("成功删除信息");
            }
            SearchGridView();
        }

        private void button2_Click(object sender, EventArgs e) {
            FrmWebServiceNew frmWebServiceNew = new FrmWebServiceNew(string.Empty, string.Empty, string.Empty, datGridView);
            frmWebServiceNew.ShowDialog();  //ShowDialog(); 使用ShowDialog就会死锁掉之前的程序让其不能动
            SearchGridView();
        }

        private void button6_Click(object sender, EventArgs e) {
            if(Dgv_Other.SelectedRows[0].Cells["ID"].Value == null) {
                return;
            }
            string strID = Dgv_Other.SelectedRows[0].Cells["ID"].Value.ToString();
            string strCode = Dgv_Other.SelectedRows[0].Cells["Code"].Value.ToString();
            string strName = Dgv_Other.SelectedRows[0].Cells["Name"].Value.ToString();
            FrmWebServiceNew frmWebServiceNew = new FrmWebServiceNew(strID, strCode, strName, datGridView);
            frmWebServiceNew.Show(); //ShowDialog();
        }

        private void button9_Click(object sender, EventArgs e) {
            if(DgvBusiness.SelectedRows[0].Cells["ID"].Value == null) {
                return;
            }
            DialogResult dialogResult = MessageBox.Show("确认删除" + DgvBusiness.SelectedRows[0].Cells["Code"].Value.ToString() + "?",
                this.Text, MessageBoxButtons.OKCancel);
            if(dialogResult == DialogResult.OK) {
                //删除
                string strID = DgvBusiness.SelectedRows[0].Cells["ID"].Value.ToString();
                string strSql = "delete from TBusiness where ID =" + strID + " ; ";
                ClassDB classDB = new ClassDB();
                classDB.ExecuteTransaction(strSql);
            }
            SearchGridView2();
        }

        private void SearchGridView2() {
            string strSql = "select t.ID,t.code,t.name from TBusiness t";
            ClassDB classDB = new ClassDB();
            datGridView = classDB.ExecuteDataTable(strSql);
            DgvBusiness.DataSource = datGridView;
        }

        private void FrmClassMain_Load() {
            SearchGridView2();
            DgvBusiness.DataSource = datGridView;
            DgvBusiness.Columns[0].Visible = false;
            DgvBusiness.Columns[1].Visible = true;
            DgvBusiness.Columns[2].Visible = true;
            DgvBusiness.Columns[1].ReadOnly = true;
            DgvBusiness.Columns[2].ReadOnly = true;
            DgvBusiness.Columns[1].HeaderText = "编号";
            DgvBusiness.Columns[2].HeaderText = "名称";
        }

        private void button7_Click(object sender, EventArgs e) {
            FrmBuinessNew frmBuinessNew = new FrmBuinessNew();
            frmBuinessNew.blnNew = true;
            frmBuinessNew.ShowDialog();
            SearchGridView2();
        }

        private void button8_Click(object sender, EventArgs e) {
            if(DgvBusiness.SelectedRows[0].Cells["ID"].Value == null) {
                return;
            }
            FrmBuinessNew frmBuinessNew = new FrmBuinessNew();
            frmBuinessNew.blnNew = false;
            frmBuinessNew.ID = Convert.ToInt64(DgvBusiness.SelectedRows[0].Cells["ID"].Value);
            frmBuinessNew.strCode = DgvBusiness.SelectedRows[0].Cells["Code"].Value.ToString();
            frmBuinessNew.strName = DgvBusiness.SelectedRows[0].Cells[2].Value.ToString();
            frmBuinessNew.ShowDialog();
            SearchGridView2();
        }


        private void FrmBuinessNew_Load() {
            SearchDate();
            if(dtDataForFilePath.Rows.Count > 0) {
                if(dtDataForFilePath.Rows[0]["Kind"].ToString().Equals("1")) {
                    this.radHardDisk.Checked = true;
                    this.panel1.Enabled = true;
                    this.panel2.Enabled = false;
                } else {
                    this.radFTP.Checked = true;
                    this.panel1.Enabled = false;
                    this.panel2.Enabled = true;
                }
                //获取磁盘文件系统路径
                FilePath = dtDataForFilePath.Rows[0]["FilePath"].ToString();
                this.txtFilePath.Text = dtDataForFilePath.Rows[0]["FilePath"].ToString();
                this.textBoxURL.Text = dtDataForFilePath.Rows[0]["URL"].ToString();
                this.txtFtpPath.Text = dtDataForFilePath.Rows[0]["FTPPath"].ToString();
                this.txtUser.Text = dtDataForFilePath.Rows[0]["FtpUser"].ToString();
                this.txtPwd.Text = dtDataForFilePath.Rows[0]["ftpPWD"].ToString();
            } else {
                this.radHardDisk.Checked = true;
            }
        }

        private void SearchDate() {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("select * from TSave t");
            ClassDB classDB = new ClassDB();
            dtDataForFilePath = classDB.ExecuteDataTable(strSql.ToString());
        }

        private void btn_Save_Save_Click(object sender, EventArgs e) {
            ClassDB classDB = new ClassDB();

            int intKind = 0;
            if(radHardDisk.Checked) {
                intKind = 1;
                if(this.txtFilePath.Text.Equals(string.Empty)) {
                    MessageBox.Show("路径不可为空");
                    this.txtFilePath.Focus();
                    return;
                }
            }

            if(radFTP.Checked) {
                intKind = 2;
                if(this.txtURL.Text.Equals(string.Empty)) {
                    MessageBox.Show("URL不可为空");
                    this.txtURL.Focus();
                    return;
                }
            }

            if(dtDataForFilePath.Rows.Count == 0) {
                DataRow dataRow = dtDataForFilePath.NewRow();
                dataRow["Kind"] = intKind;
                dataRow["FilePath"] = this.txtFilePath.Text;
                dataRow["URL"] = this.txtURL.Text;
                dataRow["FTPPath"] = this.txtFtpPath.Text;
                dataRow["FtpUser"] = this.txtUser.Text;
                dataRow["ftpPWD"] = this.txtPwd.Text;
                dtDataForFilePath.Rows.Add(dataRow);
                classDB.ExecuteBulkInsert("TSave", dtDataForFilePath);
            } else {
                StringBuilder strSql = new StringBuilder();
                strSql.AppendLine("Update TSave");
                strSql.AppendLine("Set Kind = @Kind");
                strSql.AppendLine(",FilePath = @FilePath");
                strSql.AppendLine(",URL = @URL");
                strSql.AppendLine(",FTPPath = @FTPPath");
                strSql.AppendLine(",FtpUser = @FtpUser");
                strSql.AppendLine(",ftpPWD = @ftpPWD");
                strSql.AppendLine("Where ID = @ID");
                SqlParameter sqlParameter1 = new SqlParameter("Kind", SqlDbType.SmallInt);
                sqlParameter1.Value = intKind;
                SqlParameter sqlParameter2 = new SqlParameter("FilePath", SqlDbType.NVarChar);
                sqlParameter2.Value = this.txtFilePath.Text.Trim();
                SqlParameter sqlParameter3 = new SqlParameter("URL", SqlDbType.NVarChar);
                sqlParameter3.Value = this.textBoxURL.Text.Trim();
                SqlParameter sqlParameter4 = new SqlParameter("FTPPath", SqlDbType.NVarChar);
                sqlParameter4.Value = this.txtFtpPath.Text.Trim();
                SqlParameter sqlParameter5 = new SqlParameter("FtpUser", SqlDbType.NVarChar);
                sqlParameter5.Value = this.txtUser.Text.Trim();
                SqlParameter sqlParameter6 = new SqlParameter("ftpPWD", SqlDbType.NVarChar);
                sqlParameter6.Value = this.txtPwd.Text;
                SqlParameter sqlParameter7 = new SqlParameter("ID", SqlDbType.Int);
                //sqlParameter7.Value = dtData.Rows[0]["ID"];  
                sqlParameter7.Value = dtDataForFilePath.Rows[0]["ID"];
                classDB.ExecuteNone(strSql.ToString(),
                    new SqlParameter[] { sqlParameter1, sqlParameter2, sqlParameter3, sqlParameter4, sqlParameter5, sqlParameter6, sqlParameter7 });
            }
            try {
                MessageBox.Show("保存成功！");
            } catch(Exception ex) {
                MessageBox.Show(ex.Message);
                throw;
            }
        }

        private void btn_down_Save_Click(object sender, EventArgs e) {
            double dblMM = double.Parse(this.txt_down_Hour.Text.Trim()) * 1000 * 60 * 24;
            dblMM = dblMM + double.Parse(this.txt_down_Minunter.Text.Trim()) * 1000 * 60;
            //上传文件
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("Update TSave");
            strSql.AppendLine("Set cfgFre = @cfgFre");
            strSql.AppendLine("Where ID = @ID");
            SqlParameter sqlParameter1 = new SqlParameter("cfgFre", SqlDbType.Decimal);
            sqlParameter1.Value = dblMM;
            SqlParameter sqlParameter2 = new SqlParameter("ID", SqlDbType.Int);
            sqlParameter2.Value = dtDir.Rows[0]["ID"];
            ClassDB classDB = new ClassDB();
            classDB.ExecuteNone(strSql.ToString(), new SqlParameter[] { sqlParameter1, sqlParameter2 });
            MessageBox.Show("保存成功！");
        }

        private void FrmIntfMain_Load() {
            SearchGridView3();
        }

        private void SearchGridView3() {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("Select t.ID,t.Code,t.Name");
            strSql.AppendLine(",case t.Status when 0 then '暂停'when 1 then '启动' else ''end as Status");
            strSql.AppendLine(",t.Memo from TIntf t");
            ClassDB classDB = new ClassDB();
            dtGridView = classDB.ExecuteDataTable(strSql.ToString());
            this.DgvInterface.DataSource = dtGridView;
            DgvInterface.Columns[0].Visible = false;
            DgvInterface.Columns[1].Visible = true;
            DgvInterface.Columns[2].Visible = true;
            DgvInterface.Columns[3].Visible = true;
            DgvInterface.Columns[4].Visible = true;
            DgvInterface.Columns[1].ReadOnly = true;
            DgvInterface.Columns[2].ReadOnly = true;
            DgvInterface.Columns[3].ReadOnly = true;
            DgvInterface.Columns[4].ReadOnly = true;
            DgvInterface.Columns[1].HeaderText = "编号";
            DgvInterface.Columns[2].HeaderText = "名称";
            DgvInterface.Columns[3].HeaderText = "状态";
            DgvInterface.Columns[4].HeaderText = "备注";
        }

        private void btn_Interface_New_Click(object sender, EventArgs e) {
            FrmIntfSetting frmIntfSetting = new FrmIntfSetting(string.Empty);
            frmIntfSetting.ShowDialog();
            this.SearchGridView();
            this.SearchGridView3();
            RefleshchkListFun();
        }

        private void btn_Interface_Upt_Click(object sender, EventArgs e) {
            if(DgvInterface.SelectedRows[0].Cells["Code"].Value == null) {
                return;
            }
            FrmIntfSetting frmIntfSetting = new FrmIntfSetting(DgvInterface.SelectedRows[0].Cells["Code"].Value.ToString());
            frmIntfSetting.ShowDialog();
            this.SearchGridView();
        }

        private void btn_Interface_Del_Click(object sender, EventArgs e) {
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("确定删除吗?", "删除提示", messButton);

            if(dr == DialogResult.OK)//如果点击“确定”按钮

            {

                for(int rowi = 0; rowi < DgvInterface.SelectedRows.Count; rowi++) {

                    if(DgvInterface.SelectedRows[rowi].Cells["Code"].Value == null) {
                        continue;
                    }
                    StringBuilder strSql = new StringBuilder();
                    strSql.AppendLine("Select t.* from TRule t");
                    strSql.AppendLine("Where t.ParentCode = '" + DgvInterface.SelectedRows[rowi].Cells["Code"].Value.ToString() +
                                      "'");
                    DataTable dtData = new DataTable();
                    ClassDB classDB = new ClassDB();
                    dtData = classDB.ExecuteDataTable(strSql.ToString());
                    SqlConnection conn = classDB.CreateConnection();
                    conn.Open();
                    SqlTransaction sqlTransaction = conn.BeginTransaction();
                    try {
                        strSql = new StringBuilder();
                        for(int i = 0; i < dtData.Rows.Count; i++) {
                            strSql.AppendLine("Delete from TRulelist Where ParentID = " + dtData.Rows[i]["ID"].ToString());
                            strSql.AppendLine(";");
                        }
                        classDB.ExecuteNone(strSql.ToString(), conn, sqlTransaction, null);
                        strSql = new StringBuilder();
                        strSql.AppendLine("Delete from TIntfURL Where ParentCode = '" +
                                          DgvInterface.SelectedRows[rowi].Cells["Code"].Value.ToString() + "'");
                        strSql.AppendLine(";");
                        strSql.AppendLine("Delete from TRule Where ParentCode = '" +
                                          DgvInterface.SelectedRows[rowi].Cells["Code"].Value.ToString() + "'");
                        strSql.AppendLine(";");
                        classDB.ExecuteNone(strSql.ToString(), conn, sqlTransaction, null);
                        strSql = new StringBuilder();
                        strSql.AppendLine("Delete from TIntf Where ID = '" +
                                          DgvInterface.SelectedRows[rowi].Cells["ID"].Value.ToString() + "'");
                        classDB.ExecuteNone(strSql.ToString(), conn, sqlTransaction, null);
                        sqlTransaction.Commit();
                    } catch(Exception ex) {
                        sqlTransaction.Rollback();
                        MessageBox.Show(ex.Message);
                    }
                }
                this.SearchGridView();
                this.SearchGridView3();

            }





        }

        private void btn_Interface_Start_Click(object sender, EventArgs e) {
            int[] selectedNumList = new int[DgvInterface.SelectedRows.Count];
            for(int Rowsi = 0; Rowsi < DgvInterface.SelectedRows.Count; Rowsi++) {
                selectedNumList[Rowsi] = DgvInterface.SelectedRows[Rowsi].Index;
                if(DgvInterface.SelectedRows[Rowsi].Cells["Code"].Value == null) {
                    continue;
                }
                if(DgvInterface.SelectedRows[Rowsi].Cells["Status"].Value.ToString().Equals("启动")) {
                    continue;
                }
                StringBuilder strSql = new StringBuilder();
                strSql.AppendLine("Select t.* from TRule t");
                strSql.AppendLine("Where t.ParentCode = '" + DgvInterface.SelectedRows[Rowsi].Cells["Code"].Value.ToString() +
                                  "'");
                DataTable dtData = new DataTable();
                ClassDB classDB = new ClassDB();
                dtData = classDB.ExecuteDataTable(strSql.ToString());

                string[] strRuleID;

                if(dtData.Rows.Count > 0) {
                    strRuleID = new string[dtData.Rows.Count];

                    for(int i = 0; i < dtData.Rows.Count; i++) {
                        strRuleID[i] = dtData.Rows[i]["ID"].ToString();
                    }

                    SqlParameter sqlParameter2 = new SqlParameter("ID", SqlDbType.Int);

                    strSql.AppendLine("Update TIntf set Status = 1 Where ID = @ID");

                    sqlParameter2.Value = Convert.ToInt64(DgvInterface.SelectedRows[Rowsi].Cells["ID"].Value.ToString());

                    classDB.ExecuteNone(strSql.ToString(), new SqlParameter[] { sqlParameter2 });

                    //重新计算下次执行时间
                    ClassIntf classIntf = new ClassIntf();
                    string message = classIntf.UpdateExecutionTime(strRuleID, new DateTime());
                    //service1.CacuNextExecutionTime(strRuleID, Convert.ToDateTime(dtData.Rows[0]["DBTime"].ToString()));


                }
                DgvInterface.SelectedRows[Rowsi].Cells["Status"].Value = "启动";
            }
            //this.SearchGridView4();
            DgvInterface.Rows[0].Selected = false;
            for(int i = 0; i < selectedNumList.Count(); i++) {
                DgvInterface.Rows[selectedNumList[i]].Selected = true;
            }

        }
        private void SearchGridView4() {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("Select t.ID,t.Code,t.Name");
            strSql.AppendLine(",case t.Status when 0 then '暂停'when 1 then '启动' else ''end as Status");
            strSql.AppendLine(",t.Memo from TIntf t");

            ClassDB classDB = new ClassDB();
            dtGridView = classDB.ExecuteDataTable(strSql.ToString());

            this.DgvInterface.DataSource = dtGridView;
            DgvInterface.Columns[0].Visible = false;
            DgvInterface.Columns[1].Visible = true;
            DgvInterface.Columns[2].Visible = true;
            DgvInterface.Columns[3].Visible = true;
            DgvInterface.Columns[4].Visible = true;

            DgvInterface.Columns[1].ReadOnly = true;
            DgvInterface.Columns[2].ReadOnly = true;
            DgvInterface.Columns[3].ReadOnly = true;
            DgvInterface.Columns[4].ReadOnly = true;

            DgvInterface.Columns[1].HeaderText = "编号";
            DgvInterface.Columns[2].HeaderText = "名称";
            DgvInterface.Columns[3].HeaderText = "状态";
            DgvInterface.Columns[4].HeaderText = "备注";


        }

        private void btn_Interface_Stop_Click(object sender, EventArgs e) {
            int[] selectedNumList = new int[DgvInterface.SelectedRows.Count];

            for(int i = 0; i < DgvInterface.SelectedRows.Count; i++) {
                selectedNumList[i] = DgvInterface.SelectedRows[i].Index;
                if(DgvInterface.SelectedRows[i].Cells["Code"].Value == null) {
                    continue;
                }

                if(DgvInterface.SelectedRows[i].Cells["Status"].Value.ToString().Equals("暂停")) {
                    continue;
                }
                ClassDB classDB = new ClassDB();

                SqlConnection conn = classDB.CreateConnection();
                conn.Open();
                SqlTransaction sqlTransaction = conn.BeginTransaction();
                try {
                    StringBuilder strSql = new StringBuilder();

                    SqlParameter sqlParameter2 = new SqlParameter("ID", SqlDbType.Int);

                    strSql.AppendLine("Update TIntf set Status = 0 Where ID = @ID");

                    sqlParameter2.Value = Convert.ToInt64(DgvInterface.SelectedRows[i].Cells["ID"].Value.ToString());

                    classDB.ExecuteNone(strSql.ToString(), conn, sqlTransaction, new SqlParameter[] { sqlParameter2 });
                    sqlTransaction.Commit();
                    DgvInterface.SelectedRows[i].Cells["Status"].Value = "暂停";
                } catch(Exception ex) {

                    sqlTransaction.Rollback();
                    MessageBox.Show(ex.Message);
                }

            }

            //this.SearchGridView4();
            DgvInterface.Rows[0].Selected = false;
            for(int i = 0; i < selectedNumList.Count(); i++) {
                DgvInterface.Rows[selectedNumList[i]].Selected = true;
            }

        }
        #region 文件日志查询部分
        private void FrmLog_Load() {
            DataTable dtBusiness = this.serachBusinessCode();
            comboBoxDMSList.SelectedIndex = 0;
            DataRow dr = dtBusiness.NewRow();
            dr["Code"] = string.Empty;
            dr["Name"] = string.Empty;
            dtBusiness.Rows.InsertAt(dr, 0);
            this.comBusiness2.DataSource = dtBusiness;
            this.comBusiness2.ValueMember = "Code";
            this.comBusiness2.DisplayMember = "Name";
            DataTable dtSysCode = this.serachSysCode();
            foreach(DataRow item in dtSysCode.Rows) {
                this.chkListSys2.Items.Add(item["SysCode"].ToString());
            }

            DataTable dtChkList = this.serachFileLogIntfCode();
            foreach(DataRow item in dtChkList.Rows) {
                this.chkListFun2.Items.Add(item["Code"].ToString());
            }
        }


        private DataTable serachBusinessCode() {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("Select t.code,t.name from TBusiness t");
            DataTable dtData = new DataTable();
            ClassDB classDB = new ClassDB();
            dtData = classDB.ExecuteDataTable(strSql.ToString());
            return dtData;
        }

        private DataTable serachFileLogIntfCode() {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("Select t.code from TIntf t");
            DataTable dtData = new DataTable();
            ClassDB classDB = new ClassDB();
            dtData = classDB.ExecuteDataTable(strSql.ToString());
            return dtData;
        }


        private DataTable serachSysCode() {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("Select distinct t.SysCode from Tsidelist t");
            DataTable dtData = new DataTable();
            ClassDB classDB = new ClassDB();
            dtData = classDB.ExecuteDataTable(strSql.ToString());
            return dtData;
        }
        #endregion

        private void BtnFileLogSearch_Click(object sender, EventArgs e) {
            string strIN = string.Empty;
            for(int i = 0; i < chkListFun2.Items.Count; i++) {
                if(chkListFun2.GetItemChecked(i)) {
                    strIN = strIN + "'" + chkListFun2.GetItemText(chkListFun2.Items[i]) + "',";
                }
            }



            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("Select t.ID,t.FileName");
            strSql.AppendLine(",t.IntfCode,t.SysCode,t.BusinessCode");
            strSql.AppendLine(",case t.Status when 0 then '未发送'");
            strSql.AppendLine("			      when 1 then '已发送' end as Status");
            strSql.AppendLine(",t.FileDir,t.UpTime,t.DownTime from TFileLog t");
            strSql.AppendLine("Where 1 = 1");
            if(!this.comBusiness2.SelectedValue.ToString().Equals(string.Empty)) {
                strSql.AppendLine("and t.BusinessCode = '" + this.comBusiness2.SelectedValue.ToString() + "'");
            }
            if(!strIN.Equals(string.Empty)) {
                strIN = strIN.Remove(strIN.Length - 1, 1);
                strSql.AppendLine("and t.IntfCode in (" + strIN + ")");
            }
            strIN = string.Empty;
            for(int i = 0; i < chkListSys2.Items.Count; i++) {
                if(chkListSys2.GetItemChecked(i)) {
                    strIN = strIN + "'" + chkListSys2.GetItemText(chkListSys2.Items[i]) + "',";
                }
            }
            if(!strIN.Equals(string.Empty)) {
                strIN = strIN.Remove(strIN.Length - 1, 1);
                strSql.AppendLine("and t.SysCode in (" + strIN + ")");
            }
            if(this.CbNotSend.Checked && this.CbSended.Checked) {

            } else if(this.CbNotSend.Checked) {
                strSql.AppendLine("and t.Status = 0");
            } else if(this.CbSended.Checked) {
                strSql.AppendLine("and t.Status = 1");
            }
            strSql.AppendLine("and t.UpTime > @startTime");
            strSql.AppendLine("and t.UpTime <= @endTime");
            SqlParameter sqlParameter1 = new SqlParameter("startTime", SqlDbType.DateTime);
            sqlParameter1.Value = new DateTime(DtpSendDataBegin.Value.Year, DtpSendDataBegin.Value.Month, DtpSendDataBegin.Value.Day, 0, 0, 0);
            SqlParameter sqlParameter2 = new SqlParameter("endTime", SqlDbType.DateTime);
            sqlParameter2.Value = new DateTime(DtpSendDataEnd.Value.Year, DtpSendDataEnd.Value.Month, DtpSendDataEnd.Value.Day, 23, 59, 59); ;
            strSql.AppendLine("and t.UpTime > @startTime1");
            strSql.AppendLine("and t.UpTime <= @endTime1");
            SqlParameter sqlParameter3 = new SqlParameter("startTime1", SqlDbType.DateTime);
            sqlParameter3.Value = new DateTime(DtpReceiveDataBegin.Value.Year, DtpReceiveDataBegin.Value.Month, DtpReceiveDataBegin.Value.Day, 0, 0, 0);
            SqlParameter sqlParameter4 = new SqlParameter("endTime1", SqlDbType.DateTime);
            sqlParameter4.Value = new DateTime(DtpReceiveDataEnd.Value.Year, DtpReceiveDataEnd.Value.Month, DtpReceiveDataEnd.Value.Day, 23, 59, 59);

            ClassDB classDB = new ClassDB();

            DataTable dt = classDB.ExecuteDataTable(strSql.ToString(), new SqlParameter[] { sqlParameter1, sqlParameter2, sqlParameter3, sqlParameter4 });

            this.DgvFileLog.DataSource = dt;
            DgvFileLog.Columns[0].Visible = false;
            DgvFileLog.Columns[1].Visible = true;
            DgvFileLog.Columns[2].Visible = true;
            DgvFileLog.Columns[3].Visible = true;
            DgvFileLog.Columns[4].Visible = true;
            DgvFileLog.Columns[5].Visible = true;
            DgvFileLog.Columns[6].Visible = true;
            DgvFileLog.Columns[7].Visible = true;
            DgvFileLog.Columns[8].Visible = true;

            DgvFileLog.Columns[1].ReadOnly = true;
            DgvFileLog.Columns[2].ReadOnly = true;
            DgvFileLog.Columns[3].ReadOnly = true;
            DgvFileLog.Columns[4].ReadOnly = true;
            DgvFileLog.Columns[5].ReadOnly = true;
            DgvFileLog.Columns[6].ReadOnly = true;
            DgvFileLog.Columns[7].ReadOnly = true;
            DgvFileLog.Columns[8].ReadOnly = true;

            DgvFileLog.Columns[8].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

            DgvFileLog.Columns[1].HeaderText = "文件名";
            DgvFileLog.Columns[2].HeaderText = "接口方法";
            DgvFileLog.Columns[3].HeaderText = "系统编号";
            DgvFileLog.Columns[4].HeaderText = "业务编号";
            DgvFileLog.Columns[5].HeaderText = "状态";
            DgvFileLog.Columns[6].HeaderText = "文件路径";
            DgvFileLog.Columns[7].HeaderText = "上传时间";
            DgvFileLog.Columns[8].HeaderText = "下发时间";

            //if (this.dateTimePicker1.Value)
            //{

            //}
        }

        private void tabPage6_Click(object sender, EventArgs e) {

        }

        private void label19_Click(object sender, EventArgs e) {

        }

        private void Btn_Import_Click(object sender, EventArgs e) {
            if(ofdInterface.ShowDialog() == DialogResult.Cancel) {
                return;
            }
            //csv文件读取   DataTable dtForInterfaceInport;

            dtForInterfaceInport = ClassCSV.ReadCsv2(ofdInterface.FileName);

            dgvInterfaceForImport.DataSource = dtForInterfaceInport;
        }



        #region 保存表里面的信息
        private void button10_Click(object sender, EventArgs e) {
            try {

                if(dtForInterfaceInport.Rows.Count < 1) {
                    MessageBox.Show("没有需要保存的数据");
                    return;
                }
            } catch {
                return;
            }


            string Code = "";
            string Name = "";
            string BusinessCode = "";
            string UpFunction = "";
            string Uper = "";
            string DownFunction = "";
            string Downer = "";
            int MaxNum = 0;
            string Memo = "";
            int Status = 1;
            int ThreadNum = 1;
            int blnStep = 1;
            int Class = 1;
            int DataClass = 1;
            string ParentID = "";
            string ParentCode = "";
            int Kind = 1;  //日
            int blnUp = 0;
            int Frequency = 10;//发送频率
            DateTime BeginTime = new DateTime();
            DateTime EndTime = new DateTime();
            DataTable errorTable = (dgvInterfaceForImport.DataSource as DataTable).Copy();
            errorTable.Clear();
            int Countsuccess = 0;
            int failFailure = 0;
            //foreach(var row in dtForInterfaceInport)
            for(int i = 0; i < dtForInterfaceInport.Rows.Count; i++) {
                try {

                    //把数据插入数据库

                    //成功插入的在dgvInterfaceForImport ，清除改行
                    // dataGridView1.Rows.Remove(dataGridView1.SelectedRows)
                    //temp保存临时失败数目，主要是为了确定在调用其他方法时，失败数目有没有变化 2014-08-27 Edited By ZFX
                    int temp = failFailure;
                    failFailure = ExcueNew(dtForInterfaceInport.Rows[i], failFailure);
                    if(temp != failFailure) {
                        failFailure--;
                        throw new Exception("");

                    }
                    //Status = Convert.ToInt32(dtForInterfaceInport.Rows[i]["Status"]);
                    Countsuccess++;
                } catch(Exception ex) {
                    failFailure++;
                    errorTable.ImportRow(dtForInterfaceInport.Rows[i]);
                }

            }
            dgvInterfaceForImport.DataSource = errorTable;
            dtForInterfaceInport = errorTable.Copy();
            MessageBox.Show("成功上传" + Countsuccess + "数据,剩余" + failFailure + "数据上传失败,详情请查看列表信息");
            FrmIntfMain_Load();
        }
        #endregion

        #region 导入接口信息

        private int ExcueNew(DataRow dr, int ifailFailure) {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("Insert into TIntf(Code,Name,BusinessCode,UpFunction,Uper,DownFunction,Downer");
            strSql.AppendLine(",MaxNum,Memo,Status,ThreadNum,blnStep,Class,DataClass) ");
            strSql.AppendLine(" Values (");
            strSql.AppendLine("@Code,@Name,@BusinessCode,@UpFunction,@Uper,@DownFunction,@Downer");
            strSql.AppendLine(",@MaxNum,@Memo,@Status,@ThreadNum,@blnStep,@Class,@DataClass");
            strSql.AppendLine(" )");
            strSql.AppendLine(";");
            //上传URL
            if((string)dr["Uper"] == "DMS") {
                strSql.AppendLine("Insert into TIntfURL(ParentCode,SysCode,blnUp)");
                strSql.AppendLine("Values ( 'DMS','DMS',1 )");
            } else {
                strSql.AppendLine("Insert into TIntfURL(ParentCode,SysCode,blnUp)");
                strSql.AppendLine("select @Code,o.SysCode, 1 from TSide t,TSideList o");
                strSql.AppendLine("where t.ID = o.ParentID and t.Code = @Uper");
            }
            //下发URL
            if((string)dr["Downer"] == "DMS") {
                strSql.AppendLine("Insert into TIntfURL(ParentCode,SysCode,blnUp)");
                strSql.AppendLine("Values ( 'DMS','DMS',0 )");
            } else {
                strSql.AppendLine("Insert into TIntfURL(ParentCode,SysCode,blnUp)");
                strSql.AppendLine("select @Code,o.SysCode, 0 from TSide t,TSideList o");
                strSql.AppendLine("where t.ID = o.ParentID and t.Code = @Downer");
            }
            SqlParameter[] sqlParameters = this.CreateTIntfParameters(dr);
            ClassDB classDB = new ClassDB();
            SqlConnection conn = classDB.CreateConnection();
            conn.Open();
            SqlTransaction sqlTransaction = conn.BeginTransaction();
            try {
                //新增TIntf，TIntfURL
                classDB.ExecuteNone(strSql.ToString(), conn, sqlTransaction, sqlParameters);
                string sql = CreateTRuleSql();
                //DataRow[] drRows = dtRule.Select("blnUp = 1");
                string sqlUpTRuleList = CreateTRuleListSql();
                string sqlDownTRuleList = CreateTRuleListSql();
                //(DataRow dr, int TRuleListID,string UpOrDown)
                //新增上传规则
                long ID = classDB.ExecuteID(sql, conn, sqlTransaction, this.CreateTRuleParameters(dr, "Up"));
                dr["ParentID"] = ID;
                SqlParameter[] sqlUpTRuleListParameters = this.CreateTRuleListParameters(dr, ID, "Up");
                classDB.ExecuteNone(sqlUpTRuleList, conn, sqlTransaction, sqlUpTRuleListParameters);
                //新增下发规则
                //drRows = dtRule.Select("blnUp = 0");
                ID = classDB.ExecuteID(sql, conn, sqlTransaction, this.CreateTRuleParameters(dr, "Down"));
                dr["ParentID"] = ID;
                SqlParameter[] sqlDownTRuleListParameters = this.CreateTRuleListParameters(dr, ID, "Down");
                classDB.ExecuteNone(sqlDownTRuleList, conn, sqlTransaction, sqlDownTRuleListParameters);
                //classDB.ExecuteBulkInsert("TRuleList", dtUpRulelist, conn, sqlTransaction);
                sqlTransaction.Commit();
                // MessageBox.Show("保存成功！");
            } catch(Exception ex) {
                sqlTransaction.Rollback();
                MessageBox.Show(ex.Message);
                ifailFailure++;
                return ifailFailure;
            }
            conn.Close();
            conn.Dispose();
            return ifailFailure;
        }

        private SqlParameter[] CreateTIntfParameters(DataRow dr) {
            SqlParameter sqlParCode = new SqlParameter("Code", SqlDbType.NVarChar);
            sqlParCode.Value = dr["Code"];
            SqlParameter sqlParName = new SqlParameter("Name", SqlDbType.NVarChar);
            sqlParName.Value = dr["Name"];
            SqlParameter sqlParBusinessCode = new SqlParameter("BusinessCode", SqlDbType.NVarChar);
            sqlParBusinessCode.Value = dr["BusinessCode"];
            SqlParameter sqlParUpFunction = new SqlParameter("UpFunction", SqlDbType.NVarChar);
            sqlParUpFunction.Value = dr["UpFunction"];
            SqlParameter sqlParUper = new SqlParameter("Uper", SqlDbType.NVarChar);
            sqlParUper.Value = dr["Uper"];
            SqlParameter sqlParDownFunction = new SqlParameter("DownFunction", SqlDbType.NVarChar);
            sqlParDownFunction.Value = dr["DownFunction"];
            SqlParameter sqlParDowner = new SqlParameter("Downer", SqlDbType.NVarChar);
            sqlParDowner.Value = dr["Downer"];
            SqlParameter sqlParMaxNum = new SqlParameter("MaxNum", SqlDbType.Int);
            sqlParMaxNum.Value = dr["MaxNum"];
            SqlParameter sqlParMemo = new SqlParameter("Memo", SqlDbType.NVarChar);
            sqlParMemo.Value = dr["Memo"];
            SqlParameter sqlParStatus = new SqlParameter("Status", SqlDbType.SmallInt);
            sqlParStatus.Value = dr["Status"];
            SqlParameter sqlParThreadNum = new SqlParameter("ThreadNum", SqlDbType.Int);
            sqlParThreadNum.Value = dr["ThreadNum"];
            SqlParameter sqlParblnStep = new SqlParameter("blnStep", SqlDbType.SmallInt);
            sqlParblnStep.Value = dr["blnStep"];
            SqlParameter sqlParClass = new SqlParameter("Class", SqlDbType.SmallInt);
            sqlParClass.Value = dr["Class"];
            SqlParameter sqlParDataClass = new SqlParameter("DataClass", SqlDbType.SmallInt);
            sqlParDataClass.Value = dr["DataClass"];
            SqlParameter sqlParParentID = new SqlParameter("ParentID", SqlDbType.Int);
            sqlParParentID.Value = dr["ParentID"];
            SqlParameter[] sqlParameters = {sqlParCode,sqlParName,sqlParBusinessCode,sqlParUpFunction,sqlParUper,sqlParDownFunction,sqlParDowner,
                                           sqlParMaxNum,sqlParMemo,sqlParStatus,sqlParThreadNum,sqlParblnStep,sqlParClass,sqlParDataClass,sqlParParentID};
            return sqlParameters;
        }
        private SqlParameter[] CreateTRuleListParameters(DataRow dr, long TRuleListID, string UpOrDown) {
            SqlParameter sqlParentID = new SqlParameter("ParentID", SqlDbType.Int);
            sqlParentID.Value = TRuleListID;
            SqlParameter sqlStartTime = new SqlParameter("StartTime", SqlDbType.NVarChar);
            SqlParameter sqlParExecutionTime = new SqlParameter("EndTime", SqlDbType.NVarChar);
            if(UpOrDown == "Up") {
                sqlStartTime.Value = Convert.ToDateTime(dr["UpBeginTime"]).ToShortTimeString();
                sqlParExecutionTime.Value = dr["UpEndTime"];
            } else {
                sqlStartTime.Value = dr["DownBeginTime"];
                sqlParExecutionTime.Value = dr["DownEndTime"];
            }
            SqlParameter[] sqlParameters = { sqlParentID, sqlStartTime, sqlParExecutionTime };
            return sqlParameters;
        }

        private string CreateTRuleSql() {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("Insert into TRule(ParentCode,Kind,blnUp,Frequency,ExecutionTime,WeekDay,MonthDay)");
            strSql.AppendLine(" Values (");
            strSql.AppendLine("@ParentCode,@Kind,@blnUp,@Frequency,@ExecutionTime,@WeekDay,@MonthDay");
            strSql.AppendLine(" )");
            return strSql.ToString();
        }

        private string CreateTRuleListSql() {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine("Insert into TRuleList(ParentID,StartTime,EndTime)");
            strSql.AppendLine(" Values (");
            strSql.AppendLine("@ParentID,@StartTime,@EndTime");
            strSql.AppendLine(" )");
            return strSql.ToString();
        }

        private SqlParameter[] CreateTRuleParameters(DataRow drRule, string UpOrDown) {
            //0:下发；1:上传
            SqlParameter sqlParblnUp = new SqlParameter("blnUp", SqlDbType.SmallInt);
            SqlParameter sqlParFrequency = new SqlParameter("Frequency", SqlDbType.Int);
            SqlParameter sqlParExecutionTime = new SqlParameter("ExecutionTime", SqlDbType.DateTime);
            if(UpOrDown == "Up") {
                sqlParblnUp.Value = 1;
                sqlParFrequency.Value = drRule["UpFrequency"];
                sqlParExecutionTime.Value = drRule["UpExecutionTime"];
            } else {
                sqlParblnUp.Value = 0;
                sqlParFrequency.Value = drRule["DownFrequency"];
                sqlParExecutionTime.Value = drRule["DownExecutionTime"];
            }
            SqlParameter sqlParCode = new SqlParameter("ParentCode", SqlDbType.NVarChar);
            sqlParCode.Value = drRule["Code"];
            SqlParameter sqlParKind = new SqlParameter("Kind", SqlDbType.SmallInt);
            sqlParKind.Value = drRule["Kind"];
            SqlParameter sqlParWeekDay = new SqlParameter("WeekDay", SqlDbType.NVarChar);
            sqlParWeekDay.Value = drRule["WeekDay"];
            SqlParameter sqlParMonthDay = new SqlParameter("MonthDay", SqlDbType.NVarChar);
            sqlParMonthDay.Value = drRule["MonthDay"];
            SqlParameter[] sqlParameters = { sqlParCode, sqlParKind, sqlParblnUp, sqlParFrequency,
                                               sqlParExecutionTime, sqlParWeekDay, sqlParMonthDay };
            return sqlParameters;
        }
        #endregion

        private void button11_Click(object sender, EventArgs e) {
            SaveFileDialog SaveFile = new SaveFileDialog();
            SaveFile.FileName = "接口信息导入模板.csv";
            SaveFile.Filter = "|*.csv|所有文件(*.*)|*.*";
            SaveFile.RestoreDirectory = true;
            if(SaveFile.ShowDialog() == DialogResult.OK) {
                System.IO.File.Copy(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Model\\接口信息导入模板.csv", SaveFile.FileName, true);//文件另存为
            }
        }

        private void fontDialog1_Apply(object sender, EventArgs e) {
            FontDialog diag = new FontDialog();
            diag.ShowDialog();
        }
        public void ExportToExcel2(DataSet dataSet, string fileName) {
            //Excel程序
            Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
            excelApplication.DisplayAlerts = false;
            //工作簿
            Workbook workbook = excelApplication.Workbooks.Add(Missing.Value);
            //上一个工作簿
            Worksheet lastWorksheet = (Worksheet)workbook.Worksheets.get_Item(workbook.Worksheets.Count);
            //空白工作簿
            Worksheet[] newSheetList = new Worksheet[dataSet.Tables.Count];
            for(int i = 0; i < newSheetList.Count(); i++) {
                newSheetList[i] =
                   (Worksheet)workbook.Worksheets.Add(Type.Missing, lastWorksheet, Type.Missing, Type.Missing);
                newSheetList[i].Cells.Font.Size = 12;
            }
            int SheetListNumber = 0;
            foreach(System.Data.DataTable dt in dataSet.Tables) {
                newSheetList[SheetListNumber].Name = dt.TableName;
                for(int col = 0; col < dt.Columns.Count; col++) {
                    newSheetList[SheetListNumber].Cells[1, col + 1] = dt.Columns[col].ColumnName;
                }
                for(int row = 0; row < dt.Rows.Count; row++) {
                    for(int col = 0; col < dt.Columns.Count; col++) {
                        newSheetList[SheetListNumber].Cells[row + 2, col + 1] = dt.Rows[row][col].ToString();
                    }
                }
                SheetListNumber++;
            }
            try {
                // newSheet.Cells.Font.Size = 12;
                ((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1)).Delete();
                ((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1)).Delete();
                //((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1)).Delete();
                //((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1)).Activate();
                workbook.Close(true, fileName, System.Reflection.Missing.Value);
                // MessageBox.Show("成功导出Excel，请查看！", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            } catch(Exception e) {
                throw e;
            } finally {
                excelApplication.Quit();
                Process[] excelProcesses = Process.GetProcessesByName("EXCEL");
                DateTime startTime = new DateTime();
                int processId = 0;
                for(int i = 0; i < excelProcesses.Length; i++) {
                    if(startTime < excelProcesses[i].StartTime) {
                        startTime = excelProcesses[i].StartTime;
                        processId = i;
                    }
                }
                if(excelProcesses[processId].HasExited == false) {
                    excelProcesses[processId].Kill();
                }
            }
        }

        

        //把数据保存到Excel
        public void ExportToExcel(DataSet dataSet, string fileName) {
            //Excel程序
            Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
            excelApplication.DisplayAlerts = false;
            //工作簿
            Workbook workbook = excelApplication.Workbooks.Add(Missing.Value);
            //上一个工作簿
            Worksheet lastWorksheet = (Worksheet)workbook.Worksheets.get_Item(workbook.Worksheets.Count);

            //Worksheet lastWorksheet = (Worksheet)workbook.Worksheets.get_Item(1);
            //空白工作簿
            Worksheet[] newSheetList = new Worksheet[dataSet.Tables.Count];
            for(int i = 0; i < newSheetList.Count(); i++) {
                newSheetList[i] =
                   (Worksheet)workbook.Worksheets.Add(Type.Missing, lastWorksheet, Type.Missing, Type.Missing);
                newSheetList[i].Cells.Font.Size = 12;
            }           
            //Parallel.For(0, dataSet.Tables.Count, (TableNum) => {
            //    DataTable dt = dataSet.Tables[TableNum];
            //    newSheetList[TableNum].Name = dt.TableName;

            //    Parallel.For(0, dt.Columns.Count, (col) => {
            //        newSheetList[TableNum].Cells[1, col + 1] = dt.Columns[col].ColumnName;
            //    });
            //    Parallel.For(0, dt.Rows.Count, (row) => {
            //        for(int col = 0; col < dt.Columns.Count; col++) {
            //            newSheetList[TableNum].Cells[row + 2, col + 1] = dt.Rows[row][col].ToString();
            //        }
            //    });
            //});
            Parallel.For(0, dataSet.Tables.Count, (TableNum) => {
                DataTable dt = dataSet.Tables[TableNum];

                //if(dt.TableName.Length > 31) {
                //    MessageBox.Show("工作表名长度不能大于31，" + dt.TableName + "长度为：" + dt.TableName.Length);
                //    return;
                //}
                newSheetList[TableNum].Name = dt.TableName;
                //dtPartsPlannedWarehouseOrderList 名字超长 最长31s

                Parallel.For(0, dt.Columns.Count, (col) => {
                    newSheetList[TableNum].Cells[1, col + 1] = dt.Columns[col].ColumnName;
                });
                Parallel.For(0, dt.Rows.Count, (row) => {
                    for(int col = 0; col < dt.Columns.Count; col++) {
                        newSheetList[TableNum].Cells[row + 2, col + 1] = dt.Rows[row][col].ToString();
                    }
                });
            });

            try {
                
                //((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(0)).Delete();
                //((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1)).Delete();               
                //((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1)).Activate();  

                //转换的时候多了一个Sheet1删除掉
                ((Worksheet)workbook.Worksheets[1]).Delete();
                workbook.Close(true, fileName, System.Reflection.Missing.Value);                
                return;
            } catch(Exception e) {
                throw e;
            } finally {
                excelApplication.Quit();
                Process[] excelProcesses = Process.GetProcessesByName("EXCEL");
                DateTime startTime = new DateTime();
                int processId = 0;
                Parallel.For(0, excelProcesses.Length, (i) => {
                    if(startTime < excelProcesses[i].StartTime) {
                        startTime = excelProcesses[i].StartTime;
                        processId = i;
                    }
                });
                if(excelProcesses[processId].HasExited == false) {
                    excelProcesses[processId].Kill();
                }
            }
        }


        public static void ToExcelSheet(DataSet ds, string fileName) {
            //int testnum = ds.Tables.Count-1;

            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();

            fileName = saveDialog.FileName;
            if(fileName.IndexOf(":") < 0) return; //被点了取消

            Microsoft.Office.Interop.Excel.Application appExcel;
            appExcel = new Microsoft.Office.Interop.Excel.Application();
            if(appExcel == null) {
                MessageBox.Show("无法创建Excel对象，可能您的机子未安装Excel");
                return;
            }

            Microsoft.Office.Interop.Excel.Workbook workbookData;
            Microsoft.Office.Interop.Excel.Worksheet worksheetData;
            Range range;
            workbookData = appExcel.Workbooks.Add(System.Reflection.Missing.Value);

            appExcel.DisplayAlerts = false;//不显示警告
            //xlApp.Visible = true;//excel是否可见
            //
            //for (int i = workbookData.Worksheets.Count; i > 0; i--)
            //{
            //    Microsoft.Office.Interop.Excel.Worksheet oWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbookData.Worksheets.get_Item(i);
            //    oWorksheet.Select();
            //    oWorksheet.Delete();
            //}

            for(int k = 0; k < ds.Tables.Count; k++) {
                worksheetData = (Microsoft.Office.Interop.Excel.Worksheet)workbookData.Worksheets.Add(System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);

                // testnum--;
                if(ds.Tables[k] != null) {
                    worksheetData.Name = ds.Tables[k].TableName;
                    //写入标题
                    for(int i = 0; i < ds.Tables[k].Columns.Count; i++) {
                        worksheetData.Cells[1, i + 1] = ds.Tables[k].Columns[i].ColumnName;
                        range = (Range)worksheetData.Cells[1, i + 1];
                        range.Interior.ColorIndex = 15;
                        range.Font.Bold = true;
                        range.NumberFormatLocal = "@";//文本格式 
                        // range.EntireColumn.AutoFit();//自动调整列宽 
                        // range.WrapText = true; //文本自动换行   
                        range.ColumnWidth = 15;

                    }
                    //写入数值

                    for(int r = 0; r < ds.Tables[k].Rows.Count; r++) {
                        for(int i = 0; i < ds.Tables[k].Columns.Count; i++) {

                            worksheetData.Cells[r + 2, i + 1] = ds.Tables[k].Rows[r][i];
                            //Range myrange = worksheetData.get_Range(worksheetData.Cells[r + 2, i + 1], worksheetData.Cells[r + 3, i + 2]);

                            //myrange.NumberFormatLocal = "@";//文本格式 
                            //// myrange.EntireColumn.AutoFit();//自动调整列宽 
                            ////   myrange.WrapText = true; //文本自动换行   
                            //myrange.ColumnWidth = 15;

                        }
                        //  rowRead++;

                        System.Windows.Forms.Application.DoEvents();

                    }

                }

                worksheetData.Columns.EntireColumn.AutoFit();
                workbookData.Saved = true;

            }


            workbookData.SaveAs(fileName);
            workbookData.Close();

            appExcel.Quit();
            //DialogResult btn = MessageBox.Show(null, "文件“" + fileName + "”保存成功。是否现在打开？", "信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

            //if(btn == DialogResult.Yes) {
            //    ApplicationClass excelApp = new ApplicationClass();
            //    Workbook workbook2 = excelApp.Workbooks.Open(fileName);
            //    excelApp.Visible = true;

            //}
            // appExcel.Quit();


            GC.Collect();
        }


        public bool DeleteSheet(String ExcelFilePath, String SaveSheetNames) {
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            try {
                Workbook workbook1 = excel.Workbooks.Open(ExcelFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);         //完成目标表
                Worksheet worksheet = null;
                for(int i = 0; i < excel.Worksheets.Count; i++) {
                    if(SaveSheetNames == ((Worksheet)excel.Worksheets[i]).Name) {
                        worksheet = (Worksheet)workbook1.Worksheets[i];
                        if(MessageBox.Show("是否删除已存在的“" + SaveSheetNames + "”Sheet页？", "系统提示", MessageBoxButtons.YesNo) == DialogResult.Yes) {
                            excel.DisplayAlerts = false; //注意一定要加上这句
                            ((Worksheet)workbook1.Worksheets[i]).Delete();
                            excel.DisplayAlerts = true;//注意一定要加上这句
                        } else {
                            return false;
                        }
                    }
                }
                workbook1.Close(XlSaveAction.xlSaveChanges, Missing.Value, Missing.Value);               // 保存并关闭这个工作簿。
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook1);
                workbook1 = null;
                //workbook1.Close(false, Type.Missing, Type.Missing);
                //System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook1);
                //excel.DisplayAlerts = false;
            } catch(System.Exception ex) {
                MessageBox.Show("出错");
                //    LastError = string.Format("WdCalcCode类\n," + ex.Message, "系统提示");
                //    return bRetFlag;
            } finally {
                excel.Quit();
                excel = null;
                GC.Collect();
            } return true;
        }

        #region 查看XML发送或者保存的信息
        private void BtnForReadTheFile_Click(object sender, EventArgs e) {
            //打开磁盘文件系统坐在路径
            ofdInterface.InitialDirectory = FilePath;
            //ofdInterface.Multiselect = true;
            if(ofdInterface.ShowDialog() == DialogResult.Cancel) {
                return;

            }
            DataSet dataCSV = new DataSet();
            urlForDataInport = ofdInterface.FileName;
            FileStream fs = new FileStream(ofdInterface.FileName, FileMode.Open);
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            dataCSV = DataCompress.DataSetConvertFromByte(bytes, true);
            dsForDataInport = dataCSV.Copy();
            
            dgvForReadTheFile.DataSource = dataCSV.Tables[0];
            //如果有清单，就显示第一个清单
            if (dataCSV.Tables.Count>1) 
              dgvForReadTheFileList.DataSource = dataCSV.Tables[1];
        }
        #endregion

        private void button12_Click(object sender, EventArgs e) {
            XmlDocument doc = new XmlDocument();
            Cmb_Style.SelectedValue = "";
            doc.Load(StyleUrl);
            XmlNode root = doc.DocumentElement;
            XmlNode DMS = root.SelectSingleNode("DMS");
            DMS.InnerText = Cmb_Style.Text;
            doc.Save(StyleUrl);
        }

        #region 保存数据
        private void BtnForSaveTheFile_Click(object sender, EventArgs e) {
            try {

                Stopwatch sw = new Stopwatch();
                sw.Start();
                if(!string.IsNullOrEmpty(urlForDataInport) && dsForDataInport.Tables.Count > 0) {

                    DataSet dataCSV1 = new DataSet();
                    //ExportToExcel(dsForDataInport, urlForDataInport); 这个方法会把工作表处理倒了，不知道怎么改，就先把工作表倒过来。
                    for(int j = 0; j < dsForDataInport.Tables.Count; j++) {
                        dataCSV1.Tables.Add(dsForDataInport.Tables[dsForDataInport.Tables.Count - 1 - j].Copy());
                    }

                    urlForDataInport = urlForDataInport.Replace(".xml", ".xls");

                    ExportToExcel(dataCSV1, urlForDataInport);
                }
                string strmessage = ("耗时：" + sw.ElapsedMilliseconds + "ms(毫秒)/" +
                                     Convert.ToInt32(sw.ElapsedMilliseconds / 1000) + "S（秒）,数据保存到文件：" + urlForDataInport +
                                     "");
                tbDataUrlText.Text = strmessage;
                MessageBox.Show(strmessage);
            } catch(Exception ex) {
                MessageBox.Show("请确认是否已经安装office软件Excel");
            }
        }
        #endregion

        private void comboBoxDMSList_SelectedIndexChanged(object sender, EventArgs e) {
            RefleshchkListDMS();
        }

        private void RefleshchkListDMS() {
            DataTable dtchkListDMS = this.serachDMSCode(comboBoxDMSList.SelectedIndex);
            chkListDMS.Items.Clear();
            foreach(DataRow item in dtchkListDMS.Rows) {
                this.chkListDMS.Items.Add(item["SysCode"].ToString());
            }
        }

        private void radFTP_CheckedChanged(object sender, EventArgs e) {
            if(radFTP.Checked) {
                this.panel1.Enabled = false;
                this.panel2.Enabled = true;
            }
        }

        private void radHardDisk_CheckedChanged(object sender, EventArgs e) {
            if(radHardDisk.Checked) {
                this.panel1.Enabled = true;
                this.panel2.Enabled = false;
            }
        }

        private void BtnExportDMSModel_Click(object sender, EventArgs e) {
            SaveFileDialog SaveFile = new SaveFileDialog();
            SaveFile.FileName = "DMS信息导入模板.csv";
            SaveFile.Filter = "|*.csv|所有文件(*.*)|*.*";
            SaveFile.RestoreDirectory = true;
            if(SaveFile.ShowDialog() == DialogResult.OK) {
                System.IO.File.Copy(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Model\\DMS信息导入模板.csv", SaveFile.FileName, true);//文件另存为
            }
        }

        private void btnInterfaceQuicklyNew_Click(object sender, EventArgs e) {
            FrmIntfSettingQuickly frmIntfSettingQuickly = new FrmIntfSettingQuickly();
            frmIntfSettingQuickly.ShowDialog();
            this.SearchGridView();
            this.SearchGridView3();
            RefleshchkListFun();
        }

        private void button3_Click_1(object sender, EventArgs e) {
            if(!txbInfCode.Text.Equals(string.Empty)) {
                //var strSql = string.Format("Select t.name from TIntf t where t.Code like '%{0}%'", txbInfCode.Text);                
                var strSql = string.Format("Select t.name from TIntf t where t.name like '%{0}%'", txbInfCode.Text);
                DataTable dtData = new DataTable();
                ClassDB classDB = new ClassDB();
                dtData = classDB.ExecuteDataTable(strSql);
                if(dtData.Rows.Count > 0) {
                    for(int i = 0; i < this.chkListFun.Items.Count; i++) {

                        this.chkListFun.Items.Clear();

                    }

                    foreach(DataRow item in dtData.Rows) {
                        //this.chkListFun.Items.Add(item["Code"].ToString());
                        this.chkListFun.Items.Add(item["Name"].ToString());
                    }
                    searchCount = searchCount + 1;
                    blNameCode = 0;

                } else {
                    MessageBoxButtons messButton = MessageBoxButtons.OK;
                    DialogResult dr = MessageBox.Show("没有查找到，请重新输入", "查询提示", messButton);
                }

            } else {
                if(searchCount > 0) {
                    var strSql = string.Format("Select t.name from TIntf t where t.name like '%{0}%'", txbInfCode.Text);
                    DataTable dtData = new DataTable();
                    ClassDB classDB = new ClassDB();
                    dtData = classDB.ExecuteDataTable(strSql);
                    if(dtData.Rows.Count > 0) {
                        for(int i = 0; i < this.chkListFun.Items.Count; i++) {

                            this.chkListFun.Items.Clear();

                        }

                        foreach(DataRow item in dtData.Rows) {
                            //this.chkListFun.Items.Add(item["Code"].ToString());
                            this.chkListFun.Items.Add(item["Name"].ToString());
                        }
                        searchCount = 0;
                        blNameCode = 0;

                    }

                }
            }
        }

        private void tabPage5_Click(object sender, EventArgs e) {

        }

        private void btnIntfName_Click(object sender, EventArgs e) {
            if(!txbIntfName.Text.Equals(string.Empty)) {
                //StringBuilder strSql = new StringBuilder();
                var strSql = string.Format("Select t.ID,t.Code,t.Name,case t.Status when 0 then '暂停'when 1 then '启动' else ''end as Status,t.Memo from TIntf t where t.name like '%{0}%'", txbIntfName.Text);

                ClassDB classDB = new ClassDB();
                dtGridView = classDB.ExecuteDataTable(strSql.ToString());

                if(dtGridView.Rows.Count > 0) {
                    this.DgvInterface.DataSource = dtGridView;
                    DgvInterface.Columns[0].Visible = false;
                    DgvInterface.Columns[1].Visible = true;
                    DgvInterface.Columns[2].Visible = true;
                    DgvInterface.Columns[3].Visible = true;
                    DgvInterface.Columns[4].Visible = true;
                    DgvInterface.Columns[1].ReadOnly = true;
                    DgvInterface.Columns[2].ReadOnly = true;
                    DgvInterface.Columns[3].ReadOnly = true;
                    DgvInterface.Columns[4].ReadOnly = true;
                    DgvInterface.Columns[1].HeaderText = "编号";
                    DgvInterface.Columns[2].HeaderText = "名称";
                    DgvInterface.Columns[3].HeaderText = "状态";
                    DgvInterface.Columns[4].HeaderText = "备注";

                    searchIntfNameCount = searchIntfNameCount + 1;
                } else {

                    MessageBoxButtons messButton = MessageBoxButtons.OK;
                    DialogResult dr = MessageBox.Show("没有查找到，请重新输入", "查询提示", messButton);
                }


            } else {
                if(searchIntfNameCount > 0) {
                    var strSql = string.Format("Select t.ID,t.Code,t.Name,case t.Status when 0 then '暂停'when 1 then '启动' else ''end as Status,t.Memo from TIntf t where t.name like '%{0}%'", txbIntfName.Text);

                    ClassDB classDB = new ClassDB();
                    dtGridView = classDB.ExecuteDataTable(strSql.ToString());

                    if(dtGridView.Rows.Count > 0) {
                        this.DgvInterface.DataSource = dtGridView;
                        DgvInterface.Columns[0].Visible = false;
                        DgvInterface.Columns[1].Visible = true;
                        DgvInterface.Columns[2].Visible = true;
                        DgvInterface.Columns[3].Visible = true;
                        DgvInterface.Columns[4].Visible = true;
                        DgvInterface.Columns[1].ReadOnly = true;
                        DgvInterface.Columns[2].ReadOnly = true;
                        DgvInterface.Columns[3].ReadOnly = true;
                        DgvInterface.Columns[4].ReadOnly = true;
                        DgvInterface.Columns[1].HeaderText = "编号";
                        DgvInterface.Columns[2].HeaderText = "名称";
                        DgvInterface.Columns[3].HeaderText = "状态";
                        DgvInterface.Columns[4].HeaderText = "备注";

                        searchIntfNameCount = 0;
                    }

                }
            }
        }

        private void btnDms_Click(object sender, EventArgs e) {
            //DataTable dtchkListDMS = this.serachDMSCode(comboBoxDMSList.SelectedIndex);

            if(!txbDms.Text.Equals(string.Empty)) {
                //这种是获取多有出现在日志的Tlog的系统                
                //                var strSql = string.Format(@"select distinct(SysCode) from TLog 
                //                              where SysCode like '%{0}%' order by SysCode", txbDms.Text);
                var strSql = string.Format(@"select distinct(SysCode) from TSideList 
                              where SysCode like '%{0}%' order by SysCode", txbDms.Text);
                DataTable dtData = new DataTable();
                ClassDB classDB = new ClassDB();
                dtData = classDB.ExecuteDataTable(strSql.ToString());

                if(dtData.Rows.Count > 0) {
                    chkListDMS.Items.Clear();
                    foreach(DataRow item in dtData.Rows) {
                        this.chkListDMS.Items.Add(item["SysCode"].ToString());
                    }
                }
            }



        }

        private void button3_Click_2(object sender, EventArgs e) {
            if(!txbIntfName.Text.Equals(string.Empty)) {
                //StringBuilder strSql = new StringBuilder();
                var strSql = string.Format("Select t.ID,t.Code,t.Name,case t.Status when 0 then '暂停'when 1 then '启动' else ''end as Status,t.Memo from TIntf t where t.code like '%{0}%'", txbIntfName.Text);

                ClassDB classDB = new ClassDB();
                dtGridView = classDB.ExecuteDataTable(strSql.ToString());

                if(dtGridView.Rows.Count > 0) {
                    this.DgvInterface.DataSource = dtGridView;
                    DgvInterface.Columns[0].Visible = false;
                    DgvInterface.Columns[1].Visible = true;
                    DgvInterface.Columns[2].Visible = true;
                    DgvInterface.Columns[3].Visible = true;
                    DgvInterface.Columns[4].Visible = true;
                    DgvInterface.Columns[1].ReadOnly = true;
                    DgvInterface.Columns[2].ReadOnly = true;
                    DgvInterface.Columns[3].ReadOnly = true;
                    DgvInterface.Columns[4].ReadOnly = true;
                    DgvInterface.Columns[1].HeaderText = "编号";
                    DgvInterface.Columns[2].HeaderText = "名称";
                    DgvInterface.Columns[3].HeaderText = "状态";
                    DgvInterface.Columns[4].HeaderText = "备注";

                    searchIntfNameCount = searchIntfNameCount + 1;
                } else {

                    MessageBoxButtons messButton = MessageBoxButtons.OK;
                    DialogResult dr = MessageBox.Show("没有查找到，请重新输入", "查询提示", messButton);
                }


            } else {
                if(searchIntfNameCount > 0) {
                    var strSql = string.Format("Select t.ID,t.Code,t.Name,case t.Status when 0 then '暂停'when 1 then '启动' else ''end as Status,t.Memo from TIntf t where t.code like '%{0}%'", txbIntfName.Text);

                    ClassDB classDB = new ClassDB();
                    dtGridView = classDB.ExecuteDataTable(strSql.ToString());

                    if(dtGridView.Rows.Count > 0) {
                        this.DgvInterface.DataSource = dtGridView;
                        DgvInterface.Columns[0].Visible = false;
                        DgvInterface.Columns[1].Visible = true;
                        DgvInterface.Columns[2].Visible = true;
                        DgvInterface.Columns[3].Visible = true;
                        DgvInterface.Columns[4].Visible = true;
                        DgvInterface.Columns[1].ReadOnly = true;
                        DgvInterface.Columns[2].ReadOnly = true;
                        DgvInterface.Columns[3].ReadOnly = true;
                        DgvInterface.Columns[4].ReadOnly = true;
                        DgvInterface.Columns[1].HeaderText = "编号";
                        DgvInterface.Columns[2].HeaderText = "名称";
                        DgvInterface.Columns[3].HeaderText = "状态";
                        DgvInterface.Columns[4].HeaderText = "备注";

                        searchIntfNameCount = 0;
                    }

                }
            }
        }

        private void button4_Click_1(object sender, EventArgs e) {
            if(!txbInfCode.Text.Equals(string.Empty)) {
                //var strSql = string.Format("Select t.name from TIntf t where t.Code like '%{0}%'", txbInfCode.Text);                
                var strSql = string.Format("Select t.code from TIntf t where t.Code like '%{0}%'", txbInfCode.Text.Trim());
                DataTable dtData = new DataTable();
                ClassDB classDB = new ClassDB();
                dtData = classDB.ExecuteDataTable(strSql);
                if(dtData.Rows.Count > 0) {
                    for(int i = 0; i < this.chkListFun.Items.Count; i++) {

                        this.chkListFun.Items.Clear();

                    }

                    foreach(DataRow item in dtData.Rows) {
                        this.chkListFun.Items.Add(item["Code"].ToString());
                        //this.chkListFun.Items.Add(item["Name"].ToString());
                    }
                    searchCount = searchCount + 1;
                    blNameCode = 1;
                } else {
                    MessageBoxButtons messButton = MessageBoxButtons.OK;
                    DialogResult dr = MessageBox.Show("没有查找到，请重新输入", "查询提示", messButton);
                }

            } else {
                if(searchCount > 0) {
                    var strSql = string.Format("Select t.code from TIntf t where t.Code like '%{0}%'", txbInfCode.Text.Trim());
                    DataTable dtData = new DataTable();
                    ClassDB classDB = new ClassDB();
                    dtData = classDB.ExecuteDataTable(strSql);
                    if(dtData.Rows.Count > 0) {
                        for(int i = 0; i < this.chkListFun.Items.Count; i++) {

                            this.chkListFun.Items.Clear();

                        }

                        foreach(DataRow item in dtData.Rows) {
                            this.chkListFun.Items.Add(item["Code"].ToString());
                            //this.chkListFun.Items.Add(item["Name"].ToString());
                        }
                        searchCount = 0;
                        blNameCode = 1;
                    }

                }
            }
        }

        private void button5_Click_1(object sender, EventArgs e) {
            //打开磁盘文件系统所在路径
            //ofdInterface.InitialDirectory = FilePath;
            ofdInterface.Multiselect = true;
            if(ofdInterface.ShowDialog() == DialogResult.Cancel) {
                return;

            }


            DataSet dataCSV = new DataSet();
            DataSet dataCSV0 = new DataSet();

            string[] arrFileName;

            arrFileName = ofdInterface.FileNames;

            string sFilePath = arrFileName[0];



            string strSourceFilename = System.IO.Path.GetFileName(arrFileName[0]);

            string[] sArray = Regex.Split(strSourceFilename, "_", RegexOptions.IgnoreCase);

            //不同经销商不合并
            string sDmsName = sArray[2];
            int j = 0;

            foreach(string sFilename in arrFileName) {

                if(j > 0) {
                    string strSourceFilenameJ = System.IO.Path.GetFileName(arrFileName[j]);
                    string[] sArrayJ = Regex.Split(strSourceFilenameJ, "_", RegexOptions.IgnoreCase);

                    if(String.Compare(sDmsName, sArrayJ[2]) == 1) {
                        MessageBox.Show("请选择同经销商的数据文件！");
                        return;
                    }

                }
                j = j + 1;
            }


            string Filename = arrFileName[0].Replace(sArray[0] + "_" + sArray[1], "Combin");

            Filename = Filename.Replace(".xml", ".xls");

            iRowCount = 0;

            int i = 0;
            foreach(string sFilename in arrFileName) {

                FileStream fs = new FileStream(sFilename, FileMode.Open);
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                //dataCSV = DataCompress.DataSetConvertFromByte(bytes, true);
                dataCSV = DataCompress.DataSetConvertFromByte(bytes, true);
                dsForDataInport = dataCSV.Copy();
                //dsForDataInport = dataCSV.Tables.Add();

                //dgvForReadFiles.DataSource = dataCSV.Tables[0];
                if(i == 0) {
                    dataCSV0 = dataCSV.Copy();
                } else {
                    dataCSV0.Merge(dataCSV, true, MissingSchemaAction.AddWithKey);
                }
                i = i + 1;
            }

            try {
                Stopwatch sw = new Stopwatch();
                sw.Start();

                if(dataCSV0.Tables.Count > 0) {

                    DataSet dataCSV1 = new DataSet();
                    //ExportToExcel(dataCSV0, Filename); 这个方法会把工作表处理倒了，不知道怎么改，就先把工作表倒过来。
                    for(int k = 0; k < dataCSV0.Tables.Count; k++) {
                        dataCSV1.Tables.Add(dataCSV0.Tables[dataCSV0.Tables.Count - 1 - k].Copy());
                    }

                    ExportToExcel(dataCSV1, Filename);
                    //ToExcelSheet(dataCSV0, Filename); //工作表顺序也会倒
                    dgvForReadFiles.DataSource = dataCSV0.Tables[0];

                    if(dataCSV0.Tables.Count > 1) {
                        dgvForReadFilesList.DataSource = dataCSV0.Tables[1];
                    }

                }
                string strmessage = ("耗时：" + sw.ElapsedMilliseconds + "ms(毫秒)/" +
                                         Convert.ToInt32(sw.ElapsedMilliseconds / 1000) + "S（秒）,数据保存到文件：" + Filename +
                                         "");
                txtMessage.Text = strmessage;

            } catch(Exception ex) {
                MessageBox.Show("出错或没有安装office软件Excel");
            }
            ofdInterface.Multiselect = false;

            MessageBox.Show("完成！");

        }

        private void button13_Click(object sender, EventArgs e) {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = true;

            //ofd.Filter = "*.doc|*.doc";
            if(ofd.ShowDialog() == DialogResult.OK) {
                object miss = System.Reflection.Missing.Value;
                //Word.Application word = new Word.ApplicationClass();
                object fileName = ofd.FileName;
            }
        }
        private void releaseObj(object obj) {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
            GC.Collect();
        }

        private void button13_Click_1(object sender, EventArgs e) {
            //打开磁盘文件系统所在路径
            ofdInterface.InitialDirectory = FilePath;
            ofdInterface.Multiselect = true;
            if(ofdInterface.ShowDialog() == DialogResult.Cancel) {
                return;

            }


            

            string[] arrFileName;

            arrFileName = ofdInterface.FileNames;

            string sFilePath = arrFileName[0];

            int i = 0;
            foreach(string sFilename in arrFileName) {
                DataSet dataCSV = new DataSet();
                DataSet dataCSV1 = new DataSet();
                FileStream fs = new FileStream(sFilename, FileMode.Open);
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                dataCSV = DataCompress.DataSetConvertFromByte(bytes, true);
                //DataSet dsForDataInport1 = dataCSV.Copy();
                //dgvForReadFiles.DataSource = dataCSV.Tables[0];

                //ExportToExcel(dataCSV, Filename); 这个方法会把工作表处理倒了，不知道怎么改，就先把工作表倒过来。
                for(int j = 0; j < dataCSV.Tables.Count; j++) {
                    dataCSV1.Tables.Add(dataCSV.Tables[dataCSV.Tables.Count-1-j].Copy());
                }
                

                try {

                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    string Filename = "";
                    if(!string.IsNullOrEmpty(sFilename) && dataCSV.Tables.Count > 0) {
                        Filename = sFilename.Replace(".xml", ".xls");
                        ExportToExcel(dataCSV1, Filename);
                        

                        i = i + 1;
                    }
                    string strmessage = ("耗时：" + sw.ElapsedMilliseconds + "ms(毫秒)/" +
                                         Convert.ToInt32(sw.ElapsedMilliseconds / 1000) + "S（秒）,数据保存到文件：" + Filename +
                                         "");
                    txtMessage.Text = strmessage;                    

                } catch(Exception ex) {
                    MessageBox.Show("请确认是否已经安装office软件Excel");
                }

            }

            ofdInterface.Multiselect = false;

            MessageBox.Show("完成！");
            //if(i == 1) {
            //    dgvForReadFiles.DataSource = dataCSV.Tables[0];

            //    if(dataCSV.Tables.Count > 1) {
            //        dgvForReadFilesList.DataSource = dataCSV.Tables[1];
            //    }
            //}
        }



       


        private IFileStorageService FileStorageService {
            get;
            set;
        }

        private void button15_Click(object sender, EventArgs e) {


            try {

                //打开磁盘文件系统坐在路径
                ofdInterface.InitialDirectory = FilePath;
                //ofdInterface.DefaultExt = ".xls";
                //ofdInterface.Filter = "xlsx file|*.xls";
                //ofdInterface.Multiselect = true;
                if(ofdInterface.ShowDialog() == DialogResult.Cancel) {
                    return;

                }

                //DataSet dataCSV = GetDataSet(ofdInterface.FileName);
                DataSet dataCSV = GetDataSet(ofdInterface.FileName);


                string strSourceFilename = System.IO.Path.GetFileName(ofdInterface.FileName);
                string[] sArray = Regex.Split(strSourceFilename, "_", RegexOptions.IgnoreCase);
                var now = DateTime.Now;
                string Filename = "";
                string strNow = string.Format("{0:HHmmss_fff}", now);
                if(sArray[0] == "Combin") {
                    Filename = ofdInterface.FileName.Replace(sArray[0], strNow);

                } else {
                    Filename = ofdInterface.FileName.Replace(sArray[0] + "_" + sArray[1], strNow);

                }

                Filename = Filename.Replace("Error", "");
                Filename = Filename.Replace(".xlsx", "");

                byte[] bytes = IntfClass.DataCompress.DataSetConvertToByte(dataCSV, true);
                System.IO.File.WriteAllBytes(Filename, bytes);

            } catch(Exception ex) {
                MessageBox.Show("请确认文件是否选择正确！");
                return;
            }
            MessageBox.Show("转化完成！");
        }


        /// <summary>  
        /// 解析Excel，返回DataTable  
        /// </summary>  
        /// <param name="fileName"></param>  
        /// <returns></returns>  
        public static List<String> ImpExcelSheetName(string fileName)  
        {  
            System.Data.DataTable dt = new System.Data.DataTable();
            List<string> List = new List<string> {
            };
            try  
            {  
 
                Microsoft.Office.Interop.Excel.Application app;  
                Workbooks wbs;  
                Worksheet ws;  
                app = new Microsoft.Office.Interop.Excel.Application();  
                wbs = app.Workbooks;  
                wbs.Add(fileName);                
                for(int i = 1; i <= app.Worksheets.Count; i++)  
                {
                    ws = (Worksheet)app.Worksheets.get_Item(i);
                    List.Add(ws.Name);                    
                }                                
                return List;  
            }  
            catch (Exception ex)  
            {  
                MessageBox.Show("数据绑定Excel失败! 失败原因："+ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return List;  
            }  
       }  

        /// <summary>
        /// EXCEL数据转换DataSet
        /// </summary>
        /// <param name="filePath">文件全路径</param>
        /// <param name="search">表名</param>
        /// <returns></returns>    
        private DataSet GetDataSet(string fileName) {
            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';";
            OleDbConnection objConn = null;
            objConn = new OleDbConnection(strConn);
            objConn.Open();
            DataSet ds = new DataSet();
            //List<string> List = new List<string> { "收款金额", "代付关税", "垫付费用", "超期", "到账利润" };
            List<string> List1 = new List<string> {
            };
            List<string> List = new List<string> {
            };
            //DataTable dtSheetName = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
            //DataTable dtSheetName = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            //DataTable dtSheetName = ImpExcel(fileName);            
            //foreach(DataRow dr in dtSheetName.Rows) {
            //    if(dr["Table_Name"].ToString().Contains("$") && !dr[2].ToString().EndsWith("$")) {
            //        continue;
            //    }
            //    string s = dr["Table_Name"].ToString();
            //    List.Add(s);
            //}
            List = ImpExcelSheetName(fileName);


            try {
                for(int i = 0; i < List.Count; i++) {
                    //ds.Tables.Add(List[i]);
                    //去掉SheetName的$符号
                    ds.Tables.Add(List[i].Replace("$", ""));
                    string SheetName = List[i];
                    //string SheetName = List[i].Replace("$", "");                    
                    string strSql = "select * from [" + SheetName + "$]";
                    OleDbDataAdapter odbcCSVDataAdapter = new OleDbDataAdapter(strSql, objConn);
                    DataTable dt = ds.Tables[i];
                    odbcCSVDataAdapter.Fill(dt);

                }
                return ds;
            } catch(Exception ex) {
                return null;
            } finally {
                objConn.Close();
                objConn.Dispose();
            }
        }

        private void button14_Click(object sender, EventArgs e) {
            //打开磁盘文件系统所在路径
            //ofdInterface.InitialDirectory = FilePath;
            ofdInterface.Multiselect = true;
            if(ofdInterface.ShowDialog() == DialogResult.Cancel) {
                return;

            }


            
            DataSet dataCSV0 = new DataSet();

            string[] arrFileName;

            arrFileName = ofdInterface.FileNames;

            string sFilePath = arrFileName[0];



            string strSourceFilename = System.IO.Path.GetFileName(arrFileName[0]);

            string[] sArray = Regex.Split(strSourceFilename, "_", RegexOptions.IgnoreCase);

            //不同经销商不合并
            //string sDmsName = sArray[2];
            //int j = 0;

            //foreach(string sFilename in arrFileName) {

            //    if(j > 0) {
            //        string strSourceFilenameJ = System.IO.Path.GetFileName(arrFileName[j]);
            //        string[] sArrayJ = Regex.Split(strSourceFilenameJ, "_", RegexOptions.IgnoreCase);

            //        if(String.Compare(sDmsName, sArrayJ[2]) == 1) {
            //            MessageBox.Show("请选择同经销商的数据文件！");
            //            return;
            //        }

            //    }
            //    j = j + 1;
            //}


            string Filename = arrFileName[0].Replace(sArray[0] + "_" + sArray[1], "Combin");

            

            iRowCount = 0;

            int i = 0;
            foreach(string sFilename in arrFileName) {

                DataSet dataCSV = new DataSet();

                FileStream fs = new FileStream(sFilename, FileMode.Open);
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                dataCSV = GetDataSet(sFilename);

                
                if(i == 0) {
                    dataCSV0 = dataCSV.Copy();
                } else {
                    dataCSV0.Merge(dataCSV, true, MissingSchemaAction.AddWithKey);
                }
                i = i + 1;
            }

            //try {
            //    Stopwatch sw = new Stopwatch();
            //    sw.Start();

            //    if(dataCSV0.Tables.Count > 0) {

            //        DataSet dataCSV1 = new DataSet();
            //        //ExportToExcel(dataCSV0, Filename); 这个方法会把工作表处理倒了，不知道怎么改，就先把工作表倒过来。
            //        for(int k = 0; k < dataCSV0.Tables.Count; k++) {
            //            dataCSV1.Tables.Add(dataCSV0.Tables[dataCSV0.Tables.Count - 1 - k].Copy());
            //        }

            //        ExportToExcel(dataCSV1, Filename);
                    
            //        dgvForReadFiles.DataSource = dataCSV0.Tables[0];

            //        if(dataCSV0.Tables.Count > 1) {
            //            dgvForReadFilesList.DataSource = dataCSV0.Tables[1];
            //        }

            //    }
            //    string strmessage = ("耗时：" + sw.ElapsedMilliseconds + "ms(毫秒)/" +
            //                             Convert.ToInt32(sw.ElapsedMilliseconds / 1000) + "S（秒）,数据保存到文件：" + Filename +
            //                             "");
            //    txtMessage.Text = strmessage;

            //} catch(Exception ex) {
            //    MessageBox.Show("出错或没有安装office软件Excel");
            //}
            ExportToExcel(dataCSV0, Filename);
            ofdInterface.Multiselect = false;

            MessageBox.Show("完成！");
        }


        //private void txbInfCode_KeyDown(object sender, KeyEventArgs e) {


        //    //var temp = Console.ReadKey();
        //    //char key = temp.KeyChar;
        //    //if(key.Equals('\r')) {
        //    //    KeyEventArgs e2 = new KeyEventArgs(Keys.Enter);
        //    //    button3_Click_1(sender, e2);
        //    //}
        //}



    }
}
